Fruit Into Baskets
Medium · sliding window
A farmer walks along one straight row of fruit trees. The list fruits describes the row: fruits[i] is the kind of fruit that grows on tree i, written as a whole number.
The farmer carries exactly two baskets. Each basket can hold as many fruits as you like, but only one kind of fruit. The farmer chooses any tree to start at, then walks right, picking exactly one fruit from every tree in turn with no skipping. The walk ends when they reach a tree whose fruit would not fit in either basket, or when the row runs out.
Return the largest number of fruits the farmer can pick in one walk.
Examples
Example 1
Input: fruits = [4, 7, 4]
Output: 3
Only two kinds appear, so the farmer can pick from every tree.
Example 2
Input: fruits = [5, 1, 9, 9, 9]
Output: 4
Start at the second tree: kinds 1 and 9 fill both baskets and the walk covers four trees.
Example 3
Input: fruits = [2, 3, 4, 5]
Output: 2
A third kind always arrives after two trees.
Constraints
- 1 <= len(fruits) <= 10^5
- 0 <= fruits[i] < 10^9