Maximum Bags With Full Capacity of Rocks - Problem
You have n bags numbered from 0 to n - 1. You are given two 0-indexed integer arrays capacity and rocks. The i-th bag can hold a maximum of capacity[i] rocks and currently contains rocks[i] rocks.
You are also given an integer additionalRocks, the number of additional rocks you can place in any of the bags.
Return the maximum number of bags that could have full capacity after placing the additional rocks in some bags.
Input & Output
Example 1 — Basic Case
$
Input:
capacity = [2,3,4,5], rocks = [1,0,1,4], additionalRocks = 2
›
Output:
2
💡 Note:
Bags need [1,3,3,1] rocks respectively. With 2 additional rocks, we can fill bags 0 and 3 (need 1 each), giving us 2 full bags total.
Example 2 — Already Full Bags
$
Input:
capacity = [10,2,2], rocks = [2,2,0], additionalRocks = 100
›
Output:
3
💡 Note:
Bag 1 is already full. Bag 0 needs 8 rocks, bag 2 needs 2 rocks. We can fill both with 100 additional rocks, so all 3 bags are full.
Example 3 — Insufficient Rocks
$
Input:
capacity = [5,5,5], rocks = [0,0,0], additionalRocks = 4
›
Output:
0
💡 Note:
Each bag needs 5 rocks to be full, but we only have 4 additional rocks. Cannot fill any bag completely.
Constraints
- 1 ≤ n ≤ 105
- capacity.length == rocks.length == n
- 1 ≤ capacity[i] ≤ 109
- 0 ≤ rocks[i] ≤ capacity[i]
- 1 ≤ additionalRocks ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Bags with capacities [2,3,4,5], current rocks [1,0,1,4], additional rocks: 2
2
Calculate Needs
Each bag needs [1,3,3,1] more rocks to be full
3
Greedy Fill
Fill bags needing 1 rock each first, result: 2 bags full
Key Takeaway
🎯 Key Insight: Greedy approach works - always fill the bags requiring the fewest additional rocks first
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code