Fruits Into Baskets III - Problem
You are a warehouse manager organizing fruits into baskets with limited capacities. You have n different types of fruits and n baskets, each with specific capacity constraints.
Problem: Given two arrays fruits and baskets, where:
fruits[i]represents the quantity of the i-th type of fruitbaskets[j]represents the capacity of the j-th basket
Rules for placement:
- Process fruits from left to right (index 0 to n-1)
- Each fruit type must be placed in the leftmost available basket with sufficient capacity
- Each basket can hold only one type of fruit
- If no suitable basket exists, the fruit type remains unplaced
Goal: Return the number of fruit types that cannot be placed in any basket.
Example: If fruits = [3, 1, 4] and baskets = [2, 5, 1], then fruit type 0 (quantity 3) goes to basket 1 (capacity 5), fruit type 1 (quantity 1) goes to basket 2 (capacity 1), and fruit type 2 (quantity 4) cannot fit anywhere, so the answer is 1.
Input & Output
example_1.py โ Basic Case
$
Input:
fruits = [3, 1, 4], baskets = [2, 5, 1]
โบ
Output:
1
๐ก Note:
Fruit 0 (qty 3) goes to basket 1 (capacity 5). Fruit 1 (qty 1) goes to basket 2 (capacity 1). Fruit 2 (qty 4) cannot fit in remaining basket 0 (capacity 2), so 1 fruit type remains unplaced.
example_2.py โ All Fit
$
Input:
fruits = [1, 2, 3], baskets = [3, 2, 1]
โบ
Output:
0
๐ก Note:
Fruit 0 (qty 1) goes to basket 0 (capacity 3). Fruit 1 (qty 2) goes to basket 1 (capacity 2). Fruit 2 (qty 3) cannot fit in basket 2, but all fruits are placed, so 0 unplaced.
example_3.py โ None Fit
$
Input:
fruits = [5, 6, 7], baskets = [1, 2, 3]
โบ
Output:
3
๐ก Note:
No fruit can fit in any basket since all fruit quantities exceed all basket capacities. All 3 fruit types remain unplaced.
Constraints
- 1 โค fruits.length โค 105
- baskets.length == fruits.length
- 1 โค fruits[i], baskets[i] โค 109
- Each basket can hold at most one type of fruit
- Fruits must be processed in left-to-right order
Visualization
Tap to expand
Understanding the Visualization
1
Boxes Arrive
Fruits arrive on conveyor belt in order, each with a specific quantity
2
Find Leftmost Bin
For each box, find the leftmost available bin with sufficient capacity
3
Assign or Reject
If suitable bin found, assign box; otherwise, box remains unplaced
Key Takeaway
๐ฏ Key Insight: The challenge is efficiently finding the leftmost available basket with sufficient capacity. Advanced data structures like segment trees reduce this from O(n) per fruit to O(log n).
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code