Maintained by Vikas Dulgunde, software engineer
You walk along a single row of trees. Each tree gives one type of fruit, encoded as an integer in the array. You carry two baskets, and each basket can hold only one fruit type, so across your whole walk you may collect at most two different types.
You may begin at any tree, but once you start you must take one fruit from every tree as you move right, never skipping. The moment you reach a tree whose type matches neither basket, you have to stop.
Because you can pick your starting tree freely, the question becomes: which contiguous stretch of trees contains the most fruits while spanning no more than two distinct types? The answer is the length of that stretch.
Return that maximum count of fruits.
The whole row uses only types 1 and 2, which fit in the two baskets, so all three trees can be picked.
Starting at index 1 gives [1, 2, 2], using types 1 and 2. Including the leading 0 would force a third type, so 3 is the best.
The stretch [2, 3, 2, 2] from index 1 to 4 holds only types 2 and 3 across four trees, which beats any window that includes the opening 1.
Visible test cases
Reframe the story: you are looking for the longest contiguous subarray that contains at most two distinct values. The baskets are just a cap of two on the number of types in your window.
A window that grows from the right and shrinks from the left fits this perfectly. Track how many of each type currently sit inside the window with a hash map keyed by fruit type.
Whenever adding a new tree pushes the number of distinct types above two, advance the left edge and decrement counts until exactly two types remain, then record the window length.
Try every possible starting tree, then extend rightward while the running set of distinct types stays at two or fewer, and keep the longest such extension.
Maintain one window that always holds at most two distinct types. Expand the right edge through every tree, and when a third type appears, shrink the left edge until the window is valid again. The best window length seen is the answer.