#904

Fruit Into Baskets

Medium Variable window, at most 2 kinds

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Trees in a row each give one fruit type. With two baskets (one type each), pick from a contiguous stretch of trees. Return the most fruit you can collect.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: longest stretch with at most two kinds of fruit.

Why this works: keep counts per kind in the window; when a third kind enters, shrink from the left until one kind disappears.

Example: [1, 2, 3, 2, 2]

[1, 2] ok, add 3 → three kinds → drop 1[2, 3, 2, 2] → length 4

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Leaving zero-count keys in the map, so map.size() stays too large.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1) — at most 3 keys.
Topic: Sliding Window
🎬 Episode 10: video coming soon