 All Problems
Fruits Into Baskets
medium
sliding window
hash map
arrays
amazon
google
facebook

You are visiting a farm with a row of fruit trees. Each tree produces one type of fruit. You have two baskets and each basket can hold only one type of fruit. Starting from any tree, you want to pick as many fruits as possible without skipping any tree. Return the maximum number of fruits you can pick.

Example 1:

Input: 1 2 1
Output: 3
Explanation: Pick all fruits.

Example 2:

Input: 0 1 2 2
Output: 3
Explanation: Trees [1,2,2].

Example 3:

Input: 1 2 3 2 2
Output: 4
Explanation: Trees [2,3,2,2].

Constraints:

  • 1 ≤ fruits.length ≤ 10⁵
  • 0 ≤ fruits[i] < fruits.length

Input format: One line — space-separated array of fruit types.

Output format: Maximum number of fruits.

Run to check your code against the sample cases, or submit to run every case