904. Fruit Into Baskets
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an array fruits
where fruits[i]
is an integer representing the type of fruit the i-th
tree produces.
You want to collect as much fruit as possible. However, the owner has a rule that you can only collect fruit from at most two different types of trees at any point. Given the array fruits
, your task is to return the maximum number of fruits you can collect under the given rule.
fruits
be empty?
fruits
array are non-negative?
fruits
array are non-negative.fruits
array?
To solve this problem, we can utilize the sliding window technique. Here’s a step-by-step plan:
Sliding Window Technique: This approach will help us efficiently keep track of the types of fruits and their counts within a dynamic window that moves across the array.
start
and end
to represent the current window.end
pointer and add the fruit at fruits[end]
to the dictionary.start
side until we are back to having at most two types of fruits.The time complexity of this approach is O(n), where n is the length of the fruits
array. Each fruit is added and removed from the dictionary at most once.
def totalFruit(fruits):
from collections import defaultdict
start, max_fruits = 0, 0
fruit_count = defaultdict(int)
# Iterate over the end pointer
for end in range(len(fruits)):
fruit_count[fruits[end]] += 1
# If we have more than 2 types of fruits, shrink the window from the start
while len(fruit_count) > 2:
fruit_count[fruits[start]] -= 1
if fruit_count[fruits[start]] == 0:
del fruit_count[fruits[start]]
start += 1
# Update the maximum number of fruits we have seen so far
max_fruits = max(max_fruits, end - start + 1)
return max_fruits
# Example Usage:
fruits = [1, 2, 1]
print(totalFruit(fruits)) # Output: 3
In this implementation:
fruit_count
to keep track of the count of each type of fruit within the sliding window.start
pointer helps in shrinking the window when there are more than two types of fruits.max_fruits
to keep track of the largest window size that contains at most two types of fruits.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?