Problem Description
Given n bags, each with a maximum capacity and a current number of rocks, determine the maximum number of bags that can be filled to full capacity by optimally distributing a given number of additional rocks.
Key Insights
- Calculate the additional rocks needed for each bag to be full by subtracting the current rocks from its capacity.
- Sort these required rocks values in ascending order.
- Use a greedy approach: iterate over the sorted list and use your available additional rocks to fill bags starting from the smallest requirement.
- Stop when you run out of rocks for the next bag.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the list of required rocks.
Space Complexity: O(n) for storing the additional rock requirements.
Solution
The problem can be solved by first computing how many additional rocks each bag needs to become full. Then, after sorting these values, use a greedy strategy to distribute the available rocks starting with the bag that requires the fewest rocks. This approach maximizes the count of fully filled bags.
The main data structures used are:
- An array to store the deficit (additional rocks required) for each bag.
- Sorting is applied to this array.
The algorithm is straightforward:
- Compute the difference (capacity[i] - rocks[i]) for each bag.
- Sort the differences.
- Iterate through the sorted differences while subtracting each from additionalRocks. Increase the count of fully filled bags until additionalRocks is insufficient for the next bag.