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.
1import java.util.*;
2
3class Solution {
4 public int maxBagsFull(int[] capacity, int[] rocks, int additionalRocks) {
5 int n = capacity.length;
6 int[] diffs = new int[n];
7 for (int i = 0; i < n; i++) {
8 diffs[i] = capacity[i] - rocks[i];
9 }
10 Arrays.sort(diffs);
11 int count = 0;
12 for (int diff : diffs) {
13 if (additionalRocks >= diff) {
14 additionalRocks -= diff;
15 count++;
16 } else {
17 break;
18 }
19 }
20 return count;
21 }
22}
This Java solution follows a similar logic as the Python solution. It first computes the deficits, sorts them, and then utilizes the additional rocks to maximize the full count of bags, iterating through the sorted list.
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 maxBagsFull(capacity, rocks, additionalRocks):
4 diffs = [c - r for c, r in zip(capacity, rocks)]
5 heapq.heapify(diffs)
6 count = 0
7 while diffs and additionalRocks >= diffs[0]:
8 smallest = heapq.heappop(diffs)
9 additionalRocks -= smallest
10 count += 1
11 return count
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.