You are given n bags. For each bag, you know its maximum capacity and the number of rocks currently inside it. You are also given an integer additionalRocks, representing extra rocks you can distribute among the bags however you want. Your objective is to place the extra rocks to maximize the number of bags that are completely full (where rocks == capacity).
This is a pure Greedy Algorithm problem with a sorting component. It acts as an excellent screening question. It tests whether a candidate can identify the bottleneck (the difference between capacity and current rocks) and realize that filling the bags that require the least amount of effort yields the highest count of full bags.
This problem strictly relies on Sorting and Greedy Resource Allocation.
deficit[i] = capacity[i] - rocks[i]. This is how many extra rocks the bag needs to become full.deficit array in ascending order. (Bags that need 0 rocks are first, bags that need 1 rock are next, etc.).deficit array. If your additionalRocks is greater than or equal to the current deficit, subtract the deficit from your additionalRocks and increment your full_bags_count.Capacities: [2, 3, 4, 5], Current Rocks: [1, 2, 4, 4], Additional Rocks: 2.
[1, 1, 0, 1].[0, 1, 1, 1].Candidates sometimes try to use a Priority Queue (Min-Heap) to solve this. While a Min-Heap conceptually works perfectly by popping the smallest deficit, inserting all elements into a heap takes and popping them takes . Sorting the deficit array in-place takes but has much less overhead and simpler code. A more fundamental mistake is not sorting at all and trying to fill bags chronologically, which completely fails the greedy premise.
For the Maximum Bags With Full Capacity coding problem, do not mutate the original capacity or rocks arrays. Create a brand new array int[] deficits. This isolates the only piece of data you actually care about (the difference). Sorting this single array keeps your logic mathematically pure and your code incredibly readable.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find Minimum Time to Finish All Jobs II | Medium | Solve | |
| Maximize Happiness of Selected Children | Medium | Solve | |
| Maximum Element After Decreasing and Rearranging | Medium | Solve | |
| Destroying Asteroids | Medium | Solve | |
| Maximum Number of Consecutive Values You Can Make | Medium | Solve |