Fruit Into Baskets
MediumSliding Window
Decode it first. Clues, constraints, pattern and plan before any code.Trees stand in a row and fruits[i] is the type of fruit on tree i. You have two baskets, and each basket holds only one type of fruit (as much of it as you like). You pick a starting tree and move right, taking one fruit from every tree, and you must stop at the first tree whose fruit fits neither basket. Return the most fruit you can collect.
In other words: find the longest contiguous subarray with at most 2 distinct values.
fruits = [1, 2, 1] → 3
fruits = [0, 1, 2, 2] → 3 (start at index 1: [1, 2, 2])
fruits = [1, 2, 3, 2, 2] → 4 ([2, 3, 2, 2])Constraints
1 <= fruits.length <= 10^50 <= fruits[i] < fruits.length