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
Fruit Into Baskets INPUT Farm with fruit trees in a row: 1 Tree 0 2 Tree 1 1 Tree 2 fruits array: 1 2 1 [0] [1] [2] Two baskets available: Basket 1 Basket 2 ALGORITHM STEPS 1 Sliding Window Use left, right pointers 2 Track Fruit Types HashMap: type to count 3 Expand Window Move right, add fruits 4 Shrink if needed If types > 2, move left Window expands over array: 1 2 1 Window: all 3 fruits map: {1:2, 2:1} FINAL RESULT Maximum window found: 1 2 1 Baskets filled: Basket 1 Type 1 Basket 2 Type 2 Output: 3 [OK] All fruits collected! Only 2 types (1 and 2) fit in 2 baskets Key Insight: This is a classic sliding window problem with at most K distinct elements (K=2 baskets). Use a HashMap to track fruit counts. Expand right pointer to add fruits, shrink left pointer when types exceed 2. Time: O(n), Space: O(1) since at most 3 types in map at any time. TutorialsPoint - Fruit Into Baskets | Optimal Sliding Window Approach
Asked in
Amazon 45 Google 32 Facebook 28 Microsoft 25
78.0K Views
High Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen