#2279
Maximum Bags With Full Capacity of Rocks
MediumArrayGreedySortingGreedySortingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal approach sorts the bags based on how many additional rocks they need to reach full capacity. By filling the bags that need the least additional rocks first, we maximize the number of bags filled.
⚙️
Algorithm
3 steps- 1Step 1: Create an array of the additional rocks needed for each bag to reach full capacity.
- 2Step 2: Sort this array in ascending order.
- 3Step 3: Iterate through the sorted array, using the additional rocks to fill the bags until you run out of additional rocks.
solution.py14 lines
1# Full working Python code
2
3def maxBagsOptimal(capacity, rocks, additionalRocks):
4 needed = [capacity[i] - rocks[i] for i in range(len(capacity))]
5 needed.sort()
6 count = 0
7 for n in needed:
8 if additionalRocks >= n:
9 additionalRocks -= n
10 count += 1
11 else:
12 break
13 return count
14ℹ
Complexity note: The complexity is O(n log n) due to the sorting step, which is the most time-consuming operation in this approach.
- 1Filling bags that need the least additional rocks first maximizes the number of bags filled.
- 2Sorting helps in efficiently determining which bags to fill.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.