Leetcode 904: Fruit Into Baskets

grid47
grid47
Exploring patterns and algorithms
Aug 8, 2024 6 min read

You are visiting a farm where fruit trees are planted in a single row from left to right. Each tree produces one type of fruit, represented by an integer array fruits, where fruits[i] is the type of fruit the ith tree produces. You have two baskets, and each basket can hold an unlimited amount of one type of fruit. Starting from any tree, you must pick exactly one fruit from each tree while moving to the right until the fruits cannot fit into your baskets. Determine the maximum number of fruits you can collect.
Problem
Approach
Steps
Complexity
Input: An integer array `fruits` representing the types of fruits on trees in a row.
Example: Input: fruits = [3, 3, 1, 2, 3]
Constraints:
• 1 <= fruits.length <= 10^5
• 0 <= fruits[i] < fruits.length
Output: An integer representing the maximum number of fruits you can collect.
Example: Output: 4
Constraints:
Goal: Calculate the longest subarray containing at most two unique numbers, representing the fruit types that fit into two baskets.
Steps:
• Use a sliding window to maintain the current subarray of fruit types.
• Keep track of the frequency of each fruit type in the window.
• If the number of unique fruit types exceeds two, adjust the window size by incrementing the starting index.
• Update the maximum length of the window whenever it contains at most two unique fruit types.
Goal: Limitations and rules to follow for the solution.
Steps:
• The input array can have up to 100,000 elements.
• Each tree produces only one type of fruit.
• You can only use two baskets, each capable of holding only one type of fruit.
Assumptions:
• The fruit array is non-empty.
• Each fruit type is represented by a non-negative integer.
Input: Input: fruits = [3, 3, 1, 2, 3]
Explanation: Start picking fruits at index 0. Collect fruits from trees [3, 3, 1, 2] before encountering the third type of fruit. Maximum fruits collected: 4.

Input: Input: fruits = [1, 2, 2, 3]
Explanation: Start picking fruits at index 1. Collect fruits from trees [2, 2, 3]. Maximum fruits collected: 3.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus