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
Visualization
Time & Space Complexity
Each element is visited at most twice (once by right pointer, once by left pointer), making it linear time
HashMap stores at most 3 fruit types (temporarily when contracting window), which is constant space
Constraints
- 1 โค fruits.length โค 105
- 0 โค fruits[i] < fruits.length
- Follow-up: Can you solve this in O(n) time?