Fruit Into Baskets - Problem
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the i-th tree produces.
You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:
- You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.
- Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right.
- The picked fruits must fit in one of your baskets. Once you reach a tree with fruit that cannot fit in your baskets, you must stop.
Given the integer array fruits, return the maximum number of fruits you can pick.
Input & Output
Example 1 — Mixed Fruits
$
Input:
fruits = [1,2,1]
›
Output:
3
💡 Note:
We can collect all 3 fruits since there are only 2 distinct types (1 and 2)
Example 2 — Three Types
$
Input:
fruits = [0,1,2,2]
›
Output:
3
💡 Note:
Starting from index 1, we can collect [1,2,2] which has 2 distinct types and length 3
Example 3 — Long Sequence
$
Input:
fruits = [1,2,3,2,2]
›
Output:
4
💡 Note:
Starting from index 1, we can collect [2,3,2,2] which has 2 distinct types (2 and 3) and length 4
Constraints
- 1 ≤ fruits.length ≤ 105
- 0 ≤ fruits[i] < fruits.length
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array of fruit types [1,2,3,2,2]
2
Find Best Window
Find longest subarray with ≤ 2 distinct types
3
Output Count
Return length of best window: 4
Key Takeaway
🎯 Key Insight: This is a sliding window problem to find the longest subarray with at most 2 distinct elements
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code