Problem Description
Given two arrays, fruits and baskets, each of length n, where fruits[i] is the quantity of the ith type of fruit and baskets[j] is the capacity of the jth basket, assign each fruit to the leftmost available basket (in order) that has a capacity greater than or equal to the fruit’s quantity. Each basket can only hold one fruit type. If no such basket exists for a fruit type, the fruit remains unplaced. Return the total count of unplaced fruit types.
Key Insights
- Use a greedy two-pointer approach to simulate the assignment from left to right.
- A pointer for baskets is used to track the next available basket.
- For each fruit, move the basket pointer until you find a basket with capacity >= fruit’s quantity.
- If a basket is found, assign the fruit and move the pointer; if not, count the fruit as unplaced.
- The problem leverages the given order in both arrays, eliminating the need for sorting.
Space and Time Complexity
Time Complexity: O(n) — each fruit and basket is processed at most once. Space Complexity: O(1) — only constant extra space is used aside from the input arrays.
Solution
We use a two-pointer technique to simulate the allocation of fruits into baskets in the given order. One pointer iterates through the fruits and another pointer tracks the available baskets. For each fruit, we advance the basket pointer until we find a basket that can accommodate that fruit (i.e., the basket's capacity is greater than or equal to the fruit's quantity). If a suitable basket is found, we assign the fruit to that basket and move to the next basket. If no basket with sufficient capacity is found, the fruit remains unplaced. Finally, we count and return the number of unplaced fruits.