Fruit Into Baskets

You walk along a single row of fruit trees, where `fruits[i]` is the type of fruit the i-th tree produces. You have two baskets, and each basket can hold any amount of fruit but only one fruit type. Starting at any tree, you pick exactly one fruit from every tree while moving right, and you must stop as soon as a tree has a fruit type that fits in neither basket. Return the maximum number of fruits you can pick.

30:00

Fruit Into Baskets
medium
Free written solution
Topics
Companies

You walk along a single row of fruit trees, where fruits[i] is the type of fruit the i-th tree produces. You have two baskets, and each basket can hold any amount of fruit but only one fruit type. Starting at any tree, you pick exactly one fruit from every tree while moving right, and you must stop as soon as a tree has a fruit type that fits in neither basket. Return the maximum number of fruits you can pick.

Example 1:
Input: {"fruits":[1,2,1]}
Output: 3
Constraints:
  • 1≤fruits.length≤1051 \leq \text{fruits.length} \leq 10^5

  • 0≤fruits[i]<fruits.length0 \leq \text{fruits}[i] < \text{fruits.length}

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"fruits":[1,2,1]}

Two empty baskets, each for one fruit type. The window starts at tree 0 and best = 0.

row of trees

🍎1

0

🍊2

1

🍎1

2

baskets (one fruit type each)

empty
empty
no third basket

window

0

best

0

Variables
VariableValue
left0
best0
DepthFunction Call
Stack empty
0/7