{x}
blog image

Fruit Into Baskets

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.

 

Example 1:

Input: fruits = [1,2,1]
Output: 3
Explanation: We can pick from all 3 trees.

Example 2:

Input: fruits = [0,1,2,2]
Output: 3
Explanation: We can pick from trees [1,2,2].
If we had started at the first tree, we would only pick from trees [0,1].

Example 3:

Input: fruits = [1,2,3,2,2]
Output: 4
Explanation: We can pick from trees [2,3,2,2].
If we had started at the first tree, we would only pick from trees [1,2].

 

Constraints:

  • 1 <= fruits.length <= 105
  • 0 <= fruits[i] < fruits.length

904. Fruit Into Baskets

Problem Description

You are given an array fruits representing the types of fruits in a row of fruit trees. You have two baskets and can only pick one fruit from each tree while moving right. Each basket can hold only one type of fruit, with no limit on the quantity. Find the maximum number of fruits you can pick.

Solution Approach: Sliding Window with Hash Table

The optimal solution uses a sliding window approach with a hash table (or dictionary) to efficiently track the fruit types and their counts within the window.

  1. Initialization: We initialize a hash table cnt to store the counts of each fruit type within the current window, two pointers i (right) and j (left) defining the window boundaries, and ans to store the maximum number of fruits collected.

  2. Sliding Window: The i pointer iterates through the fruits array. For each fruit x at index i, we increment its count in cnt.

  3. Window Size Check: If the number of unique fruit types (len(cnt)) exceeds 2 (we only have two baskets), we shrink the window from the left. We decrement the count of the fruit at index j in cnt. If its count becomes 0, we remove it from cnt. We increment j to move the left boundary.

  4. Update Maximum: After each step, we update ans with the maximum of ans and (i - j + 1) (the current window size).

  5. Return Result: After the loop finishes, ans holds the maximum number of fruits that could be collected.

Time and Space Complexity

  • Time Complexity: O(n), where n is the length of the fruits array. Each element is visited and processed at most twice (once by i and potentially once by j).
  • Space Complexity: O(1). The hash table cnt will store at most 3 unique fruit types, making its size constant regardless of the input array size.

Code Implementation (Python)

from collections import Counter
 
class Solution:
    def totalFruit(self, fruits: List[int]) -> int:
        cnt = Counter()
        ans = j = 0
        for i, x in enumerate(fruits):
            cnt[x] += 1
            while len(cnt) > 2:
                y = fruits[j]
                cnt[y] -= 1
                if cnt[y] == 0:
                    cnt.pop(y)
                j += 1
            ans = max(ans, i - j + 1)
        return ans

Code Implementation (Java)

import java.util.HashMap;
import java.util.Map;
 
class Solution {
    public int totalFruit(int[] fruits) {
        Map<Integer, Integer> cnt = new HashMap<>();
        int ans = 0;
        for (int i = 0, j = 0; i < fruits.length; ++i) {
            int x = fruits[i];
            cnt.put(x, cnt.getOrDefault(x, 0) + 1);
            while (cnt.size() > 2) {
                int y = fruits[j++];
                cnt.put(y, cnt.get(y) - 1);
                if (cnt.get(y) == 0) {
                    cnt.remove(y);
                }
            }
            ans = Math.max(ans, i - j + 1);
        }
        return ans;
    }
}

Implementations in other languages (C++, Go, TypeScript, Rust) would follow a similar structure, adapting the syntax and data structures accordingly. The core algorithm remains the same, leveraging the sliding window and hash table approach for optimal efficiency.