Standard Bar Sliding Window · Medium Problems O(n) · O(1)
A farm worker walks a single row of trees, each tree bearing exactly one fruit of a given type, and may carry only two crates — one per fruit type, but each with unlimited capacity. Starting anywhere and moving strictly rightward, they must pick from every tree they pass and stop the moment a third fruit type appears. The forecaster wants the largest haul achievable.
Input: An integer array fruits where fruits[i] is the fruit type of tree i.
Output: Return the maximum number of fruits collectible from one contiguous run of trees using at most two types.
1 <= fruits.length <= 10^50 <= fruits[i] < fruits.lengthInput: {"fruits":[2,1,2]}
Output: 3
Two types across three trees fit the two crates exactly.
Input: {"fruits":[1,2,3,2,2]}
Output: 4
Starting at tree 1 lets the picker ride types 2 and 3 through four trees.