LeetCode 2279: Maximum Bags With Full Capacity of Rocks Solution

Master LeetCode problem 2279 (Maximum Bags With Full Capacity of Rocks), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2279. Maximum Bags With Full Capacity of Rocks

Problem Explanation

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

:

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2279 (Maximum Bags With Full Capacity of Rocks)?

This page provides optimized solutions for LeetCode problem 2279 (Maximum Bags With Full Capacity of Rocks) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2279 (Maximum Bags With Full Capacity of Rocks)?

The time complexity for LeetCode 2279 (Maximum Bags With Full Capacity of Rocks) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2279 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2279 in Java, C++, or Python.

Back to LeetCode Solutions