You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array
You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:
- You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.
- Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.
- Once you reach a tree with fruit that cannot fit in your baskets, you must stop.
Given the integer array
Output: 3
Explanation: We can pick from all 3 trees.
Output: 3
Explanation: We can pick from trees [1,2,2].
If we had started at the first tree, we would only pick from trees [0,1].
Output: 4
Explanation: We can pick from trees [2,3,2,2].
If we had started at the first tree, we would only pick from trees [1,2].
Constraints:
1 <= fruits.length <= 105 0 <= fruits[i] < fruits.length
Contents
Solution 1 - Using sliding window technique and a HashMap to keep how many distinguished fruit types are collected
In this approach, we are going to apply sliding window technique using two pointers
Implementation steps:
-
First, create four variables
left ,right that we will use to adjust the window, aHashMap sum to store fruit type as key and its count as value, andmaxFruits to hold the maximum fruits collected result. -
Next, run a
while loop untilright pointer reaches end of arrayfruits , and do the following:-
Take the current fruit type at
right pointer and add it to thecount map, if the key already exists, increment its count, otherwise add it with value as 1. -
Then, check if the current window is going out of bounds, that is if the size of
count map is greater than 2, since we we have only two baskets, if it is more than 2, then move the sliding window, take the fruit type atleft pointer and reduce its count by -1, if the count becomes zero, then remove that element as well, and incrementleft pointer in awhile loop. -
Next, update the
maxFruits with maximum value betweencurrent window size and the currentmaxFruits . -
At the end of while loop increment
right pointer to move to the next element infruits array.
-
Take the current fruit type at
-
Finally, return
maxFruits .
Complexity Analysis:
Time complexity: Above code runs in O(n) time, where
Space complexity: O(1), though we are using a
Above implementations source code can be found at