Fruits Into Baskets II - Problem

You are given two arrays of integers, fruits and baskets, each of length n, where fruits[i] represents the quantity of the ith type of fruit, and baskets[j] represents the capacity of the jth basket.

From left to right, place the fruits according to these rules:

  • Each fruit type must be placed in the leftmost available basket with a capacity greater than or equal to the quantity of that fruit type.
  • Each basket can hold only one type of fruit.
  • If a fruit type cannot be placed in any basket, it remains unplaced.

Return the number of fruit types that remain unplaced after all possible allocations are made.

Input & Output

Example 1 — Basic Case
$ Input: fruits = [3,1,2], baskets = [2,3,1]
Output: 1
💡 Note: Fruit 3 goes to basket 1 (capacity 3), fruit 1 goes to basket 0 (capacity 2), fruit 2 cannot fit in remaining basket 2 (capacity 1). One fruit remains unplaced.
Example 2 — Some Unplaced
$ Input: fruits = [4,2,1], baskets = [1,2,3]
Output: 1
💡 Note: Fruit 4 cannot fit in any basket (max capacity is 3), fruit 2 goes to basket 2 (capacity 2), fruit 1 goes to basket 1 (capacity 1). One fruit remains unplaced.
Example 3 — All Unplaced
$ Input: fruits = [5,6,7], baskets = [1,2,3]
Output: 3
💡 Note: All fruits are too large for any basket. All 3 fruits remain unplaced.

Constraints

  • 1 ≤ fruits.length, baskets.length ≤ 103
  • 1 ≤ fruits[i], baskets[i] ≤ 109

Visualization

Tap to expand
Fruits Into Baskets II INPUT fruits[] array 3 i=0 1 i=1 2 i=2 baskets[] array 2 j=0 3 j=1 1 j=2 n = 3 fruit types n = 3 baskets Fruits ALGORITHM STEPS 1 Process fruit[0]=3 Find leftmost basket >=3 basket[1]=3 OK, mark used 2 Process fruit[1]=1 Find leftmost basket >=1 basket[0]=2 OK, mark used 3 Process fruit[2]=2 Find leftmost basket >=2 basket[2]=1? No. Skip used. 4 Count unplaced All fruits placed! unplaced = 0 Basket Status After Placement basket[0]=2: fruit[1]=1 basket[1]=3: fruit[0]=3 basket[2]=1: fruit[2]=2 *wait! FINAL RESULT Placement Result 1 b[0] 3 b[1] 2 b[2] Output: 0 All fruits placed! Unplaced = 0 OK Key Insight: Greedy approach: For each fruit (left to right), scan baskets from left to find the first available basket with capacity >= fruit quantity. Mark basket as used after placement. Time: O(n^2) linear search for each fruit. Count fruits that couldn't find a valid basket. TutorialsPoint - Fruits Into Baskets II | Greedy with Linear Search
Asked in
Google 25 Amazon 20 Microsoft 15
12.0K Views
Medium Frequency
~15 min Avg. Time
580 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen