VOOZH about

URL: https://www.geeksforgeeks.org/dsa/fruit-into-baskets/

⇱ Fruit Into Baskets - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Fruit Into Baskets

Last Updated : 6 Dec, 2025

In a row of trees, the i-th tree produces fruit with type A[i]. We start at any tree of our choice, then repeatedly perform the following steps:

  • Add one piece of fruit from this tree to your baskets.
  • Move to the next tree to the right of the current tree. If there is no tree to the right, stop.

Note that we do not have any choice after the initial choice of starting tree: we must perform step 1, then step 2, then back to step 1, then step 2, and so on until we stop. we have two baskets, and each basket can carry any quantity of fruit, but we want each basket to only carry one type of fruit each. What is the Maximum amount of fruit we can collect with this procedure?

Examples:

Input: A[] = {1, 2, 3, 2, 2}
Output: 4
Explanation: We can collect {2, 3, 2, 2}. If we started at the first tree.

Input: A[] = {1, 2, 1}
Output: 3
Explanation: We can collect {1,2,1}

[Naive Approach] - O(n*n) Time and O(1) Space

The idea is to start at each tree one by one and try to collect fruits until you cannot put a fruit in either of your two baskets. For every starting position, we keep track of the types of fruits collected using a map or set. If a new fruit type appears and you already have two types in the baskets, you stop collecting. We calculate the total number of fruits collected for that starting tree, and repeat the process for all trees. Finally, we take the maximum among all starting positions.


Output
4

[Better Approach] Using Sliding Window - O(n) Time and O(1) Space

The idea is to use a sliding window to keep track of the current sequence of trees containing at most two types of fruits.

  • Start with two pointers start and end to represent the current window of trees.
  • Use a hash map to count the fruits in the window (basket[fruit_type] = count).
  • Expand the end pointer (move right) and add the fruit to the basket.
  • If the basket contains more than 2 types, shrink the window from the start until we are back to at most 2 types.
  • Keep updating the maximum window length while sliding.

This way, we scan the array only once, achieving a much more efficient solution than the naive approach.ll trees. Finally, we take the maximum among all starting positions.


Output
4


Comment
Article Tags:
Article Tags: