SDE & MLE Prep

904. Fruit Into Baskets

Problem

Trees stand in a row; fruits[i] is the type of fruit tree i grows. With two baskets that each hold one fruit type (any amount), start at any tree and pick one fruit from every tree moving right, stopping when a fruit fits no basket. Return the most fruit you can pick, i.e. the longest subarray with at most two distinct values.

Example: [1,2,3,2,2] → 4 ([2,3,2,2])

Constraints: n ≤ 10⁵.

= longest window with at most 2 distinct values. Count fruits in the window; shrink while more than 2 types.

Complexity: O(n).

class Solution:
    def totalFruit(self, fruits: List[int]) -> int:
        cnt = defaultdict(int)
        l = best = 0
        for r, f in enumerate(fruits):
            cnt[f] += 1
            while len(cnt) > 2:
                cnt[fruits[l]] -= 1
                if cnt[fruits[l]] == 0:
                    del cnt[fruits[l]]
                l += 1
            best = max(best, r - l + 1)
        return best