Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2279. Maximum Bags With Full Capacity of Rocks

ArrayGreedySorting

Explanation:

To maximize the number of bags that could have full capacity, we should prioritize filling the bags with the least amount of rocks currently in them. This way, we can distribute the additional rocks more evenly and achieve the highest number of bags at full capacity.

  1. Sort the bags based on the difference between capacity and current rocks.
  2. Iterate through the sorted bags and add additional rocks to each bag until it reaches full capacity.
  3. Count the bags that have reached full capacity and return the count as the result.

Time Complexity: O(n log n) where n is the number of bags
Space Complexity: O(n) for sorting

:

import java.util.Arrays;

class Solution {
    public int maxBagsWithFullCapacity(int[] capacity, int[] rocks, int additionalRocks) {
        int n = capacity.length;
        int[][] bags = new int[n][2];
        
        for (int i = 0; i < n; i++) {
            bags[i][0] = capacity[i] - rocks[i];
            bags[i][1] = i;
        }
        
        Arrays.sort(bags, (a, b) -> a[0] - b[0]);
        
        int fullCapacityBags = 0;
        for (int i = 0; i < n && additionalRocks > 0; i++) {
            int idx = bags[i][1];
            int remainingCapacity = capacity[idx] - rocks[idx];
            int addRocks = Math.min(remainingCapacity, additionalRocks);
            rocks[idx] += addRocks;
            additionalRocks -= addRocks;
            if (rocks[idx] == capacity[idx]) {
                fullCapacityBags++;
            }
        }
        
        return fullCapacityBags;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.