Similar Problems

Similar Problems not available

Maximum Bags With Full Capacity Of Rocks - Leetcode Solution

Companies:

LeetCode:  Maximum Bags With Full Capacity Of Rocks Leetcode Solution

Difficulty: Medium

Topics: greedy sorting array  

The Maximum Bags with Full Capacity of Rocks problem on LeetCode is a binary search problem that asks to find the maximum number of bags that can hold rocks of a given weight capacity. The problem gives an array of rocks with their weights and the capacity of each bag.

The approach to solving the problem is as follows:

  1. Initialize the left pointer to 1 and the right pointer to the sum of all rocks.

  2. While the left pointer is less than or equal to the right pointer, perform the following steps:

    a. Calculate the mid value between the left and right pointers.

    b. Initialize a variable to keep track of the number of bags.

    c. Initialize a variable to keep track of the current weight capacity of the bag.

    d. Iterate through the rocks array and for each rock, check if adding its weight to the current capacity of the bag exceeds the mid value.

    If it does, increment the bag count and reset the current weight capacity to the weight of the current rock. Otherwise, add the weight of the current rock to the current weight capacity of the bag.

    e. If the number of bags required is less than or equal to the given number of bags, update the left pointer to mid + 1. Since we want to maximize the number of bags, we can try to increase the weight capacity.

    f. If the number of bags required is greater than the given number of bags, update the right pointer to mid - 1. Since we want to minimize the weight capacity, we can try to decrease the number of bags.

  3. Return the left pointer - 1, which represents the maximum number of bags that can hold rocks of the given weight capacity.

Here is the Python code for the solution:

class Solution:
    def maximumNumberOfBags(self, nums: List[int], maxCapacity: int) -> int:
        left, right = 1, sum(nums)
        while left <= right:
            mid = (left + right) // 2
            bags = 0
            capacity = 0
            for num in nums:
                if capacity + num > mid:
                    bags += 1
                    capacity = num
                else:
                    capacity += num
            if bags + 1 <= maxCapacity:
                left = mid + 1
            else:
                right = mid - 1
        return left - 1

Time Complexity: O(n log sum), where n is the number of rocks and sum is the sum of all rocks.

Space Complexity: O(1)

Maximum Bags With Full Capacity Of Rocks Solution Code

1