Sponsored
Sponsored
This approach involves calculating how many rocks each bag needs to be full. Then, we sort these requirements in increasing order. By doing so, we ensure we fill the bags requiring fewer rocks first, maximizing the number of fully filled bags. We iterate through these sorted requirements, and while we have enough additional rocks, we fill these bags, counting the number of bags that can be fully filled.
Time Complexity: O(n log n), due to sorting the differences.
Space Complexity: O(n), for storing the differences array.
1function maxBagsFull(capacity, rocks, additionalRocks) {
2 let diffs = capacity.map((c, i) => c - rocks[i]);
3 diffs.sort((a, b) => a - b);
4 let count = 0;
5 for (let diff of diffs) {
6 if (additionalRocks >= diff) {
7 additionalRocks -= diff;
8 count++;
9 } else {
10 break;
11 }
12 }
13 return count;
14}
This JavaScript function calculates the deficit for each bag, sorts them and fills as many as possible using available additional rocks, aiming to maximize the number of full capacity bags.
Instead of sorting the entire list of differences, we can use a min-heap (priority queue) to keep track of the current smallest difference that can be fulfilled with the additional rocks. This way, we continuously fill the bags requiring the least rocks at the minimum overhead cost of tree-based structure operations. While more sophisticated, this method matches the efficiency of the sorting approach for this problem's expected input size.
Time Complexity: O(n log n), predominantly due to building and maintaining the heap.
Space Complexity: O(n), for the heap storage.
1import heapq
2
3def
This solution uses a min-heap to efficiently decide which bags to fill with additional rocks by always selecting the currently least required amount, popping it from the heap and counting the full bag if successfully filled.