#904

Fruit Into Baskets

specialist · 865 · lc medium +31 · verified · 50.6% accepted · 6,142 likes · top 39%

Description

You walk along a row of fruit trees represented by array fruits, where fruits[i] is the fruit type at position i. You carry two baskets, each restricted to a single fruit type with unlimited capacity.

Starting from any tree and moving right, pick one fruit per tree; stop the moment you encounter a fruit that fits in neither basket. Return the maximum number of fruits you can collect.

Example 1:

Input: fruits = [1,2,1]
Output: 3
Explanation: We can pick from all 3 trees.

Example 2:

Input: fruits = [0,1,2,2]
Output: 3
Explanation: We can pick from trees [1,2,2].
If we had started at the first tree, we would only pick from trees [0,1].

Example 3:

Input: fruits = [1,2,3,2,2]
Output: 4
Explanation: We can pick from trees [2,3,2,2].
If we had started at the first tree, we would only pick from trees [1,2].

Code

1
2
3