Fruit Into Baskets

Solution For Fruit Into Baskets

The Fruit Into Baskets problem on LeetCode asks us to find the maximum number of fruits we can collect given that we have 2 baskets and each basket can hold only one type of fruit. We are given an array of integers where each integer represents the type of fruit. Our task is to find the length of the longest subarray that contains only two types of fruits.

Let’s walk through the solution step by step:

  1. We initialize two variables: maxFruits and typesCount. maxFruits will keep track of the maximum number of fruits we can collect and typesCount will keep track of the types of fruit currently in the basket.

  2. We initialize two pointers: start and end. Both start and end will initially be at the first element of the array.

  3. We create a while loop that will run until the end pointer reaches the end of the array. Inside the loop, we check if the current fruit at the end pointer is already in the basket. If it is, we simply increment the end pointer and continue to the next iteration. If it is not, we need to check if we can add another type of fruit to the basket. If we can, we add the fruit to the basket, increment typesCount, and move the end pointer. If we can’t add another fruit to the basket, we move the start pointer, remove the fruit from the basket (decrement typesCount), and continue to move the start pointer until it reaches the position where we can add another fruit to the basket.

  4. At every iteration, we also update the maxFruits variable to keep track of the maximum number of fruits we can collect.

  5. After the loop ends, we return the maxFruits variable as our solution.

Here is the Python code for the solution:

“`
def totalFruit(tree: List[int]) -> int:
maxFruits = 0
typesCount = 0 # number of types we have in the basket
baskets = {}
start = end = 0

while end < len(tree):
    fruit = tree[end]
    if fruit in baskets:
        baskets[fruit] += 1
    else:
        if typesCount < 2:
            baskets[fruit] = 1
            typesCount += 1
        else:
            # we need to remove a fruit from the basket
            while typesCount >= 2:
                basketFruit = tree[start]
                baskets[basketFruit] -= 1
                if baskets[basketFruit] == 0:
                    typesCount -= 1
                    del baskets[basketFruit]
                start += 1
            baskets[fruit] = 1
            typesCount += 1
    end += 1
    maxFruits = max(maxFruits, end - start)

return maxFruits

“`

The time complexity of this solution is O(n) because we iterate through the array only once. The space complexity is O(1) because we only store two types of fruits in the basket at any given time.

Step by Step Implementation For Fruit Into Baskets

In this problem, we are given an array of integers where each integer represents a type of fruit. We are also given two baskets, and our goal is to fill each basket with fruit such that we maximize the number of different types of fruit in each basket.

One solution is to keep track of the most recent two types of fruit in each basket. We can do this by keeping two variables, one for each basket. Each time we encounter a new type of fruit, we check if it is the same as the type in the first basket. If so, we swap it with the second basket. If not, we add it to the second basket. This ensures that each basket always contains two different types of fruit.

public void fruitIntoBaskets(int[] fruit) {
    int firstBasket = 0;
    int secondBasket = 1;
    
    for (int i = 0; i < fruit.length; i++) {
        if (fruit[i] == fruit[firstBasket]) {
            // swap fruits
            int temp = fruit[i];
            fruit[i] = fruit[secondBasket];
            fruit[secondBasket] = temp;
        } else {
            // add fruit to second basket
            secondBasket++;
            fruit[secondBasket] = fruit[i];
        }
    }
    
    // at this point, firstBasket and secondBasket represent the indices of the last two types of fruit in each basket
    System.out.println("First basket: " + (secondBasket - firstBasket + 1));
    System.out.println("Second basket: " + (fruit.length - secondBasket + 1));
}
In this problem, we are given an array of fruits and told to find the length of the longest subarray where no more than two different types of fruits are present.

One approach to solving this problem is to keep track of the most recently seen fruit type, as well as the second most recently seen fruit type. We can then iterate through the array, updating these values as we go. If at any point we see a third different fruit type, we can reset our counter and start again. This approach is demonstrated in the code below:

def fruit_into_baskets(fruits):
    most_recent_fruit = None
    second_most_recent_fruit = None
    longest_subarray = 0
    current_subarray = 0
    
    for fruit in fruits:
        if fruit == most_recent_fruit or fruit == second_most_recent_fruit:
            # This fruit is one of the types we're already tracking, so we can
            # simply increment our subarray counter
            current_subarray += 1
        else:
            # This is a new fruit type, so we need to reset our counter
            current_subarray = 1
            
            # Update our most recently seen fruit types
            second_most_recent_fruit = most_recent_fruit
            most_recent_fruit = fruit
        
        # Update the longest subarray if necessary
        longest_subarray = max(longest_subarray, current_subarray)
    
    return longest_subarray
var totalFruit = function(tree) {
    // create a map to keep track of the types of fruit and their respective counts
    let fruitCounts = new Map();
    
    // initialize left and right pointers
    let left = 0;
    let right = 0;
    
    // initialize a variable to keep track of the longest subarray with at most 2 types of fruit
    let longestSubarray = 0;
    
    // while the right pointer is less than the length of the input array
    while (right < tree.length) {
        // if the map does not have a key for the current type of fruit
        if (!fruitCounts.has(tree[right])) {
            // add the current type of fruit to the map with a count of 1
            fruitCounts.set(tree[right], 1);
        } else { // otherwise
            // increment the count for the current type of fruit by 1
            fruitCounts.set(tree[right], fruitCounts.get(tree[right]) + 1);
        }
        
        // while the map has more than 2 types of fruit
        while (fruitCounts.size > 2) {
            // if the current type of fruit is in the map
            if (fruitCounts.has(tree[left])) {
                // decrement the count for the current type of fruit by 1
                fruitCounts.set(tree[left], fruitCounts.get(tree[left]) - 1);
                
                // if the current type of fruit is no longer in the map
                if (fruitCounts.get(tree[left]) === 0) {
                    // remove the current type of fruit from the map
                    fruitCounts.delete(tree[left]);
                }
            }
            
            // increment the left pointer by 1
            left++;
        }
        
        // update the longest subarray if necessary
        longestSubarray = Math.max(longestSubarray, right - left + 1);
        
        // increment the right pointer by 1
        right++;
    }
    
    // return the longest subarray
    return longestSubarray;
};
In this problem, we are given an array of fruits, and we need to find the length of the longest subarray where no two fruits are the same.

One solution is to use a set to keep track of the fruits we have seen so far. We can iterate through the array, and for each fruit, we add it to the set and check if the size of the set is greater than the longest subarray we have seen so far. If so, we update the longest subarray.

set seen; int longest = 0; for (int i = 0; i < fruits.size(); i++) { seen.insert(fruits[i]); if (seen.size() > longest) longest = seen.size(); } return longest;
public int TotalFruit(int[] tree) {
        //keep track of the types of fruits in the baskets
        HashSet types = new HashSet();
        //keep track of the most recent indices of the types of fruits in the baskets
        Dictionary indices = new Dictionary();
        int maxFruit = 0;
        int start = 0;
        
        for (int i = 0; i < tree.Length; i++) {
            //if the current type of fruit is not in the baskets, add it
            if (!types.Contains(tree[i])) {
                types.Add(tree[i]);
                indices.Add(tree[i], i);
            } else {
                //if the current type of fruit is already in the baskets, update its most recent index
                indices[tree[i]] = i;
            }
            
            //if there are more than 2 types of fruit in the baskets, remove the type of fruit that was added earliest
            if (types.Count > 2) {
                int minIndex = int.MaxValue;
                int minType = 0;
                foreach (var type in types) {
                    if (indices[type] < minIndex) {
                        minIndex = indices[type];
                        minType = type;
                    }
                }
                types.Remove(minType);
                indices.Remove(minType);
                start = minIndex + 1;
            }
            
            maxFruit = Math.Max(maxFruit, i - start + 1);
        }
        
        return maxFruit;
    }


Scroll to Top

Top 100 Leetcode Practice Problems In Java

Get 30% Off Instantly!
[gravityforms id="5" description="false" titla="false" ajax="true"]