MediumNo. 2279

Maximum Bags With Full Capacity of Rocks — LeetCode 2279 Python Solution

Pattern
Greedy
Topics
Greedy, Array, Sorting
Reading time
3 min

The problem

You have n bags numbered from 0 to n - 1. You are given two 0-indexed integer arrays capacity and rocks.

Example

Input
capacity = [2,3,4,5], rocks = [1,2,4,4], additionalRocks = 2
Output
3
Explanation
Place 1 rock in bag 0 and 1 rock in bag 1.

Python solution

PythonSolution
class Solution:
    def maximumBags(
        self, capacity: List[int], rocks: List[int], additionalRocks: int
    ) -> int:
        for i, x in enumerate(rocks):
            capacity[i] -= x
        capacity.sort()
        for i, x in enumerate(capacity):
            additionalRocks -= x
            if additionalRocks < 0:
                return i
        return len(capacity)

Complexity

Time
O(n log n)
Space · auxiliary
O(1) to O(n)

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2279. Maximum Bags With Full Capacity of Rocks is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
2271Maximum White Tiles Covered by a CarpetMedium
0179Largest NumberMedium
0324Wiggle Sort IIMedium
0452Minimum Number of Arrows to Burst BalloonsMedium
0455Assign CookiesEasy
0502IPOHard

Frequently asked questions

How hard is LeetCode 2279. Maximum Bags With Full Capacity of Rocks?

LeetCode 2279. Maximum Bags With Full Capacity of Rocks is rated Medium on LeetCode.

What topics does LeetCode 2279. Maximum Bags With Full Capacity of Rocks cover?

LeetCode 2279. Maximum Bags With Full Capacity of Rocks is tagged Greedy, Array and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.