Back to Dashboard

Fruit Into Baskets

Medium

Problem Statement

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 ith 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.

Examples

Example 1:

  • Input: fruits = [1,2,1]
  • Output: 3

Approach 1 Sliding Window:

class Solution {
    public int totalFruit(int[] fruits) {
        var fruitMap = new HashMap<Integer, Integer>();
        var windowStart = 0;
        var maxCount = 0;
        var curCount = 0;
        for (int windowEnd = 0; windowEnd < fruits.length; windowEnd ++) {
            curCount += 1;
            fruitMap.put(fruits[windowEnd], fruitMap.getOrDefault(fruits[windowEnd], 0) + 1);
            if (fruitMap.size() > 2) {
                fruitMap.put(fruits[windowStart], fruitMap.get(fruits[windowStart]) - 1);
                if (fruitMap.get(fruits[windowStart]) == 0) {
                    fruitMap.remove(fruits[windowStart]);
                }
                curCount --;
                windowStart ++;
            }
            maxCount = Math.max(maxCount, curCount);
        }
        return maxCount;
    }
}

Status

Solved

Complexity

Time
O(n)
Space
O(1)

Tags

ArraySliding Window

Date

2026-02-13
View Problem Source