Fruits Into Basket
Pick the most fruit from a row of trees when each of your two baskets holds only one type.
A row of fruit trees is given as an array fruitsfruits[i]i
Example 1
Output: 3
Explanation: all three trees fit in two baskets.
Example 2
Output: 3
Explanation: pick from trees [1, 2, 2].
Example 3
Output: 4
Explanation: pick from trees [2, 3, 2, 2].
The Idea
Picture yourself walking along a row of trees with two baskets. The first type of fruit you meet goes in one basket and the second type in the other. After that, every tree must match one of the two baskets, and the first tree that matches neither ends the walk.
Take Example 3, where the trees carry the types 1, 2, 3, 2, 2. Start at tree 0: type 1 fills one basket, type 2 the other, and tree 2 has type 3, so you stop with 2 fruits. Start at tree 1 instead: types 2 and 3 fill the baskets, trees 3 and 4 add two more of type 2, and you pick 4.
Whichever tree you start at, the trees you pick from form one unbroken stretch of the row that holds at most two types. So the story asks a plain question: how long can a stretch with at most two different values be?
You could start a walk at every tree, but each walk goes over trees the previous walk has already seen. Is there a way to keep what the last walk learned? When the walk from tree 0 runs into type 3 at tree 2, the trees after tree 0 are still worth keeping. Only the front of the stretch has to go, until one type has left it completely.
So keep the stretch between two markers: leftrightrightleft
In the first row, leftrightrightleftright
The stretch between the two markers is called a window, and because both of its ends only ever move right, this way of searching is called a sliding window. Each tree enters the window once and leaves it at most once, instead of being looked at again by every walk.
Solution Approach
Turning that idea into code means settling three things: how to know which types are in the window, how far to move left
Counting the types in the window
Why not just remember the two types? Because when left
So keep a HashMap
Moving the left marker
How far should left
Is it safe that leftrightleftright
Recording the best length
When is the answer checked? After leftleftrightright - left + 1
Java Solution
The method totalFruit
- First, create the map
, from fruit type to the number of trees of that type in the window, and setcount andleft to 0.best - A loop moves
along the row, from the first tree to the last. For each tree,right adds 1 to that type's count, or puts the type in with a count of 1 if it is new.count.merge(fruits[right], 1, Integer::sum) - Inside, a
loop runs as long aswhile . It lowers the count of the type atcount.size() > 2 , removes the key when that count reaches 0, and movesleft one tree to the right.left - The window now holds at most two types, so its length
replacesright - left + 1 if it is longer.best - After the last tree, return
, the most fruit any window held.best
The mainleft
import java.util.HashMap;
import java.util.Map;
public class FruitsIntoBasket {
public static int totalFruit(int[] fruits) {
Map<Integer, Integer> count = new HashMap<>(); // fruit type -> trees in the window
int left = 0;
int best = 0;
for (int right = 0; right < fruits.length; right++) {
count.merge(fruits[right], 1, Integer::sum);
while (count.size() > 2) { // three types: drop trees from the left
int type = fruits[left];
if (count.merge(type, -1, Integer::sum) == 0) {
count.remove(type);
}
left++;
}
best = Math.max(best, right - left + 1);
}
return best;
}
public static void main(String[] args) {
System.out.println(totalFruit(new int[] {1, 2, 1}));
System.out.println(totalFruit(new int[] {0, 1, 2, 2}));
System.out.println(totalFruit(new int[] {1, 2, 3, 2, 2}));
System.out.println(totalFruit(new int[] {3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4}));
System.out.println(totalFruit(new int[] {7}));
System.out.println(totalFruit(new int[] {3, 3, 3, 3}));
}
}
Running it prints:
3
3
4
5
1
4
The answers 3, 3 and 4 on top match the three examples. The 5 on the fourth line comes from [3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4]left
The last two lines are the small cases. A single tree gives 1. The row [3, 3, 3, 3]while
Removing the key at 0 matters. If the code only lowers the count, a type with count 0 still counts as a key, so the map keeps three keys. On [1, 2, 3, 2, 2]leftArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
The original implementation,
Complexity
The work is one pass of rightleft
- Time: O(n), because
adds each of the n trees to the window once andright removes each tree at most once. That is at most 2n steps, and each map operation takes O(1) on average.left - Space: O(1). The map never holds more than three keys, because the
loop removes a type as soon as a third one enters.while
With k