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 fruits, where fruits[i] is the type of fruit on tree i. You have two baskets, and each basket holds any amount of a single type. Starting at any tree, you pick one fruit from every tree while moving right, and you must stop at the first tree whose fruit fits in neither basket. Return the most fruit you can pick.

Example 1
Input: fruits = [1, 2, 1]
Output: 3
Explanation: all three trees fit in two baskets.
Example 2
Input: fruits = [0, 1, 2, 2]
Output: 3
Explanation: pick from trees [1, 2, 2].
Example 3
Input: fruits = [1, 2, 3, 2, 2]
Output: 4
Explanation: pick from trees [2, 3, 2, 2].
Solution

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: left marks its first tree and right its last. right moves one tree at a time, and left moves only when the stretch holds three types. Look at the picture below.

The trees 1, 2, 3, 2, 2 in four rows. With right = 1 the window holds types 1 and 2. With right = 2 type 3 enters and makes three types. Then left moves to 1 and type 1 is gone. With right = 4 the window holds 2, 3, 2, 2: four trees of two types.

In the first row, left is on tree 0 and right on tree 1: types 1 and 2, a window of 2 trees. In the second row, right reaches tree 2 and type 3 enters, which makes three types. In the third row, left moves to tree 1, type 1 is gone, and two types remain. In the last row, right has reached tree 4, and the window 2, 3, 2, 2 holds 4 trees of types 2 and 3.

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, and when to record the answer.

Counting the types in the window

Why not just remember the two types? Because when left passes a tree, we need to know whether another tree of the same type is still inside. Take the trees 1, 2, 1, 3. When type 3 arrives, dropping tree 0 removes a type 1, but tree 2 still holds a type 1.

So keep a HashMap from each type to the number of trees of that type in the window. When a count drops to 0, the type has left the window, and its key is removed. The number of keys is then the number of baskets in use.

Moving the left marker

How far should left move when a third type arrives? One tree at a time, until the map has two keys again. In the trees 1, 2, 1, 3, that means passing tree 0 (type 1 still has one tree left) and then tree 1, where type 2 drops to 0 and is removed.

Is it safe that left never moves back? Any stretch that ends at right and starts before the new left holds the dropped type and the other two, so it has three types. Moving right further only adds trees, so those stretches never become allowed again.

Recording the best length

When is the answer checked? After left has moved, the window from left to right holds at most two types. Its length, right - left + 1, is the fruit you could pick from those trees, so the longest one seen is the answer.

Java Solution

The method totalFruit works in these steps:

  1. First, create the map count, from fruit type to the number of trees of that type in the window, and set left and best to 0.
  2. A loop moves right along the row, from the first tree to the last. For each tree, count.merge(fruits[right], 1, Integer::sum) adds 1 to that type's count, or puts the type in with a count of 1 if it is new.
  3. Inside, a while loop runs as long as count.size() > 2. It lowers the count of the type at left, removes the key when that count reaches 0, and moves left one tree to the right.
  4. The window now holds at most two types, so its length right - left + 1 replaces best if it is longer.
  5. After the last tree, return best, the most fruit any window held.

The main method runs the three examples, a longer row where left must pass three trees of one type, a single tree, and a row of only one type.

Java
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:

Output
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], where the best window is 1, 2, 1, 1, 2, trees 3 to 7. When type 2 first arrives at tree 4, left has to pass all three trees of type 3 before the map is back to two keys.

The last two lines are the small cases. A single tree gives 1. The row [3, 3, 3, 3] gives 4, the whole row, because one type fills only one basket and the while loop never runs.

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] that version moves left past the end of the row and stops with ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5.

The original implementation, FruitsIntoBasket.java, is on GitHub.

Complexity

The work is one pass of right over the row, plus the moves of left, which never goes back.

  • Time: O(n), because right adds each of the n trees to the window once and left removes each tree at most once. That is at most 2n steps, and each map operation takes O(1) on average.
  • Space: O(1). The map never holds more than three keys, because the while loop removes a type as soon as a third one enters.

With k baskets instead of two, this is Longest Substring with at most K Distinct Characters.