Fruit Into Baskets
You start at some tree in a row of fruit trees given by the array fruits, where fruits[i] is the fruit type on tree i. You carry two baskets, each holding a single (unlimited) fruit type, and you pick one fruit from every tree moving right until you cannot. Return the maximum number of fruits you can pick — equivalently, the length of the longest contiguous subarray containing at most two distinct values.
Open official problem prompt ↗Find the longest contiguous stretch of trees whose fruits come from at most two types.
Walking down an orchard row with exactly two baskets, you keep collecting until a third fruit type appears; then you must have started later, so you drop the oldest trees from your route until only two types remain, always remembering the longest successful walk.
- Input
- fruits = [1, 2, 3, 2, 2]
- Output
- 4
- Why
- The subarray [2, 3, 2, 2] uses only two fruit types (2 and 3) and has length 4, the longest such run.
1 <= fruits.length <= 10^50 <= fruits[i] < fruits.length