Fruit Into Baskets

Pattern: Sliding window: variable size

medium

Two baskets, one kind each, means the longest block with at most two different values. Count kinds in the window and shrink from the left when a third kind arrives.

The problem

Trees stand in a row, and fruits[i] is the kind of fruit on tree i. You have two baskets, and each basket holds only one kind of fruit (as much as you like). You pick a starting tree and walk right, taking one fruit from every tree, and you must stop at the first tree whose fruit fits in neither basket. Return the most fruit you can collect. For example, [1, 2, 1] gives 3, [0, 1, 2, 2] gives 3, and [3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4] gives 5.

The function name totalFruit matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • Strip away the story. The fruit you collect is a block of trees. What is true about that block?
  • When a third kind arrives, which trees at the start of the window must be given up?
  • How do you know when a kind has completely left the window?

Hints

    Brute force, and why it fails

    From each start, walk right until a third kind appears: O(n²). The window handles every start in one pass: O(n).

    The key insight

    This is "longest window with at most k distinct values" with k = 2. A count map tells you when the rule breaks and when a kind has fully left.

    Dry run

    30left
    31 
    32 
    13right
    24 
    15 
    16 
    27 
    38 
    39 
    410 
    kinds2
    best4

    fruits = [3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4]. The window 3, 3, 3, 1 holds two kinds and has length 4.

    Step 1 of 4

    The plan

    count = empty map, left = 0, best = 0
    for right from 0 to n - 1:
        count[fruits[right]] = count[fruits[right]] + 1
        while size of count > 2:
            count[fruits[left]] = count[fruits[left]] - 1
            if count[fruits[left]] == 0: remove fruits[left] from count
            left = left + 1
        best = max(best, right - left + 1)
    return best
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Each edge moves at most n times, and the map never holds more than three kinds.

    Edge cases

    • One tree: 1.
    • Only one or two kinds in the whole row: the answer is n.
    • The best block is at the very end, as in [1, 2, 3, 3, 3]: 4.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int totalFruit(int[] fruits) {
            Map<Integer, Integer> count = new HashMap<>();   // kind -> how many of it are in the window
            int left = 0, best = 0;
            for (int right = 0; right < fruits.length; right++) {
                count.merge(fruits[right], 1, Integer::sum);
                while (count.size() > 2) {          // a third kind: drop fruit from the left until one kind is gone
                    int kind = fruits[left];
                    if (count.merge(kind, -1, Integer::sum) == 0) count.remove(kind);
                    left++;
                }
                best = Math.max(best, right - left + 1);
            }
            return best;
        }
    }

    C++

    class Solution {
    public:
        int totalFruit(vector<int>& fruits) {
            unordered_map<int, int> count;          // kind -> how many of it are in the window
            int left = 0, best = 0;
            for (int right = 0; right < static_cast<int>(fruits.size()); right++) {
                count[fruits[right]]++;
                while (count.size() > 2) {          // a third kind: drop fruit from the left until one kind is gone
                    int kind = fruits[left];
                    if (--count[kind] == 0) count.erase(kind);
                    left++;
                }
                best = max(best, right - left + 1);
            }
            return best;
        }
    };

    Python

    class Solution:
        def totalFruit(self, fruits: list[int]) -> int:
            count = {}                              # kind -> how many of it are in the window
            left = best = 0
            for right, kind in enumerate(fruits):
                count[kind] = count.get(kind, 0) + 1
                while len(count) > 2:               # a third kind: drop fruit from the left until one kind is gone
                    old = fruits[left]
                    count[old] -= 1
                    if count[old] == 0:
                        del count[old]
                    left += 1
                best = max(best, right - left + 1)
            return best

    Common mistakes

    • Forgetting to remove a kind whose count drops to 0, so the map size never shrinks.
    • Jumping left to just after the last copy of one kind without checking the counts.
    • Answering with the number of kinds instead of the number of fruit.

    Similar problems