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
Maximum Bags With Full Capacity INPUT Bags with Capacity & Rocks Bag 0 2/1 Bag 1 3/0 Bag 2 4/1 Bag 3 5/4 Arrays: capacity: 2 3 4 5 rocks: 1 0 1 4 Rocks Needed: [1, 3, 3, 1] additionalRocks = 2 gap[i] = capacity[i] - rocks[i] ALGORITHM STEPS 1 Calculate Gaps gap[i] = capacity[i] - rocks[i] [1, 3, 3, 1] 2 Sort Gaps (Ascending) Prioritize smallest gaps [1, 1, 3, 3] 3 Fill Bags Greedily Use rocks for smallest gaps Rocks: 2 Fill gap=1: 2-1=1 [OK] Fill gap=1: 1-1=0 [OK] gap=3 needs 3, have 0 4 Count Full Bags Bags filled = 2 FINAL RESULT After Distribution: Bag 0 FULL Bag 1 0/3 Bag 2 1/4 Bag 3 FULL Output: 2 Maximum bags that can be filled = 2 Used: 1 rock for Bag 0 Used: 1 rock for Bag 3 Key Insight: The greedy approach works because filling bags with smaller gaps first maximizes the number of full bags. Sort gaps ascending, then fill until rocks run out. TutorialsPoint - Maximum Bags With Full Capacity of Rocks | Greedy Approach
Asked in
Amazon 35 Google 28 Microsoft 22 Meta 18
25.6K Views
Medium Frequency
~15 min Avg. Time
892 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