Problem Description
Given an array of integers representing fruit trees where each integer denotes the type of fruit produced, determine the maximum number of fruits that can be picked by starting at any tree and collecting exactly one fruit from each tree to the right, while only being allowed to hold two distinct types of fruits in your baskets.
Key Insights
- Use a sliding window to maintain a contiguous subarray with at most two distinct fruit types.
- A hash table (or dictionary) is used to count occurrences of fruit types in the current window.
- Expand the window to include new fruits and shrink it from the left when more than two types are present.
- This approach is similar to solving the "longest substring with at most K distinct characters" for K = 2.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the fruits array. Space Complexity: O(1), as the hash table stores at most 3 keys in worst-case scenarios (effectively bounded by 2 unique types).
Solution
We use a sliding window technique. By iterating through the fruits array with a right pointer, we update a hash table that tracks the count of each fruit type in the window. When the window contains more than two unique fruit types, we move the left pointer to reduce the window size until it becomes valid again (only two types remain). The maximum valid window size over all iterations gives the maximum number of fruits that can be picked.