Fruit Into Baskets
viaLeetCode
Problem Trees in a row each bear one fruit type (fruits[i]). With two baskets, each holding only one type, start at any tree and move right picking one fruit per tree; stop when a third type appears. Maximize fruits picked — i.e. find the longest subarray with at most 2 distinct values.
Input / Output
- Input: int array fruits. Output: max window length.
Constraints
- n up to 10^5; O(n) expected.
Example
- [1,2,3,2,2] → 4 ([2,3,2,2]); [3,3,3,1,2,1,1,2,3,3,4] → 5.
Expected approach
- Sliding window with a type → count map: extend right; when a third type enters, shrink from the left until only two remain; track the best length. O(n) time, O(1) space (≤3 keys). This is longest-substring-with-at-most-K-distinct with K = 2 — recognizing the reduction is the point.
asked …