sagelearnai

Fruit Into Baskets

Difficulty: Medium · Pattern: Sliding Window · LeetCode #904

Trees in a row produce fruit of type fruits[i]. You have two baskets, each holding one type (unlimited quantity). Starting at any tree, you pick one fruit from every tree moving right, and stop when a fruit doesn't fit either basket. Return the maximum number of fruits you can pick.

Examples

text
[1, 2, 1]        →  3
[0, 1, 2, 2]     →  3    (start at index 1: 1, 2, 2)
[1, 2, 3, 2, 2]  →  4    (2, 3, 2, 2)

Hints

  1. Restated: the longest contiguous subarray with at most 2 distinct values.
  2. Keep counts per type in the window; shrink when there are 3 types.

Approach

Sliding window with a hash map of counts. Add fruits[r]; while the map has more than 2 keys, decrement fruits[l] (deleting it at 0) and advance l. Track the best window length. The same template solves "at most k distinct".

Complexity

Time: O(n). Space: O(1) (at most 3 keys).

Python solution
def totalFruit(fruits):
    count, l, best = {}, 0, 0
    for r, f in enumerate(fruits):
        count[f] = count.get(f, 0) + 1
        while len(count) > 2:
            count[fruits[l]] -= 1
            if count[fruits[l]] == 0:
                del count[fruits[l]]
            l += 1
        best = max(best, r - l + 1)
    return best
JavaScript solution
function totalFruit(fruits) {
  const count = new Map(); let l = 0, best = 0;
  for (let r = 0; r < fruits.length; r++) {
    count.set(fruits[r], (count.get(fruits[r]) || 0) + 1);
    while (count.size > 2) {
      const f = fruits[l++]; count.set(f, count.get(f) - 1);
      if (count.get(f) === 0) count.delete(f);
    }
    best = Math.max(best, r - l + 1);
  }
  return best;
}