Fruit Into Baskets
Problem Summary
- Given a list of fruit types, and you can only have two types of fruits
- If you can only pick 1 fruit from each row, how many max can you have with you
What is Being Asked?
Key Observations
(Patterns, constraints, or hints in the problem statement.)
- Solve it in
time
Approach Taken
- Same as the other problem
Main Concepts Used
Time & Space Complexity
- Time:
→ Reason: Doing one pass - Space:
→ We are storing character to count in our map. If input is of same fruit types then it would be otherwise at max it could be 2 distinct types
Code
class Solution:
def totalFruit(self, fruits: List[int]) -> int:
MAX_FRUIT_TYPES = 2
start, max_fruits = 0, float("-inf")
map = {}
for end, end_fruit in enumerate(fruits):
map[end_fruit] = 1 + map.get(end_fruit, 0)
while len(map) > MAX_FRUIT_TYPES:
left_fruit_type = fruits[start]
map[left_fruit_type] -= 1
if map[left_fruit_type] == 0:
map.pop(left_fruit_type)
start += 1
max_fruits = max(max_fruits, end - start + 1)
return max_fruits