Leetcode 2279: Maximum Bags With Full Capacity of Rocks

grid47
grid47
Exploring patterns and algorithms
Mar 24, 2024 6 min read

You have n bags, each capable of holding a certain number of rocks. You are given two arrays: capacity where capacity[i] is the maximum number of rocks that bag i can hold, and rocks where rocks[i] is the current number of rocks in bag i. You also have additionalRocks which represents the number of rocks you can distribute into the bags. Your goal is to determine the maximum number of bags that can be filled to their capacity after placing the additional rocks in any of the bags.
Problem
Approach
Steps
Complexity
Input: You are given two arrays `capacity` and `rocks`, where each represents the capacity and current number of rocks in each bag, respectively. You are also given an integer `additionalRocks` that represents the number of rocks you can place in the bags.
Example: Input: capacity = [5, 7, 8, 3], rocks = [3, 2, 5, 2], additionalRocks = 4
Constraints:
• n == capacity.length == rocks.length
• 1 <= n <= 5 * 10^4
• 1 <= capacity[i] <= 10^9
• 0 <= rocks[i] <= capacity[i]
• 1 <= additionalRocks <= 10^9
Output: Return the maximum number of bags that can be filled to their full capacity after distributing the additional rocks.
Example: Output: 3
Constraints:
Goal: The goal is to maximize the number of bags that can be filled to their full capacity by strategically distributing the additional rocks.
Steps:
• Calculate the number of additional rocks needed to fill each bag to its capacity.
• Store the differences between the `capacity[i]` and `rocks[i]` in a sorted order to prioritize filling bags that require fewer rocks.
• Distribute the additional rocks starting from the bag that needs the least amount of rocks.
• Count how many bags can be filled completely with the available additional rocks.
Goal: The solution should efficiently handle up to 50,000 bags and large values for capacity and additionalRocks.
Steps:
Assumptions:
• You can place the additional rocks in any of the bags in any order.
Input: Input: capacity = [5, 7, 8, 3], rocks = [3, 2, 5, 2], additionalRocks = 4
Explanation: In this case, the number of rocks required to fill each bag are [2, 5, 3, 1]. We can place 2 rocks in bag 0, 1 rock in bag 3, and 1 rock in bag 1. This allows us to fill 3 bags to their full capacity. The output is 3.

Input: Input: capacity = [10, 5, 3], rocks = [4, 2, 1], additionalRocks = 6
Explanation: Here, the required rocks to fill each bag are [6, 3, 2]. We can place 3 rocks in bag 1, and 3 rocks in bag 2, filling 2 bags. The output is 2.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus