Fruit Into Baskets - Problem
Imagine you're visiting a fruit orchard where trees are arranged in a single row from left to right. Each tree produces one type of fruit, represented by an integer in the array fruits where fruits[i] is the fruit type of the i-th tree.
You want to maximize your fruit collection, but there are strict rules:
- ๐งบ You have exactly two baskets
- ๐ Each basket can only hold one type of fruit
- ๐ฆ Each basket has unlimited capacity for its fruit type
- โก๏ธ You must start at any tree and move only to the right
- ๐ You must stop when you encounter a third fruit type
Goal: Find the maximum number of fruits you can collect following these rules.
Example: For [1,2,1], you can collect all 3 fruits (types 1 and 2 fit in your two baskets).
Input & Output
example_1.py โ Basic Case
$
Input:
[1,2,1]
โบ
Output:
3
๐ก Note:
We can collect all fruits: start at index 0, collect fruit type 1, then 2, then 1 again. Both types fit in our two baskets, so we get 3 fruits total.
example_2.py โ Multiple Types
$
Input:
[0,1,2,2]
โบ
Output:
3
๐ก Note:
We can start at index 1 and collect [1,2,2]. This gives us 3 fruits with only 2 types (1 and 2). Starting at index 0 would only give us [0,1] = 2 fruits before hitting the third type.
example_3.py โ Single Type
$
Input:
[1,2,3,2,2]
โบ
Output:
4
๐ก Note:
The optimal collection is [2,3,2,2] starting from index 1, which gives us 4 fruits with types 2 and 3. Any other starting position gives fewer fruits.
Visualization
Tap to expand
Understanding the Visualization
1
Start collecting
Begin with empty baskets and start collecting fruits from left to right
2
Expand collection
Keep collecting fruits as long as you have at most 2 different types
3
Handle third type
When you encounter a third fruit type, you must abandon some fruits from the left to make room
4
Track maximum
Throughout the process, remember the largest collection you've achieved
Key Takeaway
๐ฏ Key Insight: This is essentially finding the longest contiguous subarray with at most 2 distinct elements - a perfect use case for the sliding window technique!
Time & Space Complexity
Time Complexity
O(n)
Each element is visited at most twice (once by right pointer, once by left pointer), making it linear time
โ Linear Growth
Space Complexity
O(1)
HashMap stores at most 3 fruit types (temporarily when contracting window), which is constant space
โ Linear Space
Constraints
- 1 โค fruits.length โค 105
- 0 โค fruits[i] < fruits.length
- Follow-up: Can you solve this in O(n) time?
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code