LeetCode 904: Fruit Into Baskets Solution

Master LeetCode problem 904 (Fruit Into Baskets), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

904. Fruit Into Baskets

Problem Explanation

Explanation

To solve this problem, we can use a sliding window approach. We will keep track of the types of fruits in our two baskets and the count of each type of fruit. We will iterate through the array, adding fruits to our baskets as long as the total number of distinct fruit types in our baskets is less than or equal to 2. If we encounter a third type of fruit, we will update our window by removing fruits from the beginning of the window until we can accommodate the new fruit type. We will keep track of the maximum number of fruits collected during this process.

Time complexity: O(n) where n is the number of elements in the input array. Space complexity: O(1) Java:

Solution Code

class Solution {
    public int totalFruit(int[] fruits) {
        int maxFruits = 0;
        int type1 = -1, type2 = -1, count1 = 0, count2 = 0, current = 0;
        
        for (int fruit : fruits) {
            if (fruit == type1) {
                count1++;
                current++;
            } else if (fruit == type2) {
                count2++;
                current++;
            } else {
                current = count1 + 1;
                count1 = 1;
                type1 = type2;
                count2 = 0;
                type2 = fruit;
            }
            
            if (type1 != -1 && type2 != -1) {
                maxFruits = Math.max(maxFruits, current);
            }
        }
        
        return maxFruits;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 904 (Fruit Into Baskets)?

This page provides optimized solutions for LeetCode problem 904 (Fruit Into Baskets) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 904 (Fruit Into Baskets)?

The time complexity for LeetCode 904 (Fruit Into Baskets) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 904 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 904 in Java, C++, or Python.

Back to LeetCode Solutions