HardNo. 1889
Minimum Space Wasted From Packaging — LeetCode 1889 Python Solution
- Pattern
- Prefix Sum
- Topics
- Array, Binary Search, Prefix Sum, Sorting
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You have n packages that you are trying to place in boxes, one package in each box. There are m suppliers that each produce boxes of different sizes (with infinite supply).
Example
- Input
- packages = [2,3,5], boxes = [[4,8],[2,8]]
- Output
- 6
- Explanation
- It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.
Python solution
class Solution:
def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int:
mod = 10**9 + 7
ans = inf
packages.sort()
for box in boxes:
box.sort()
if packages[-1] > box[-1]:
continue
s = i = 0
for b in box:
j = bisect_right(packages, b, lo=i)
s += (j - i) * b
i = j
ans = min(ans, s)
if ans == inf:
return -1
return (ans - sum(packages)) % modComplexity
- Time
- O(log n) or O(n log n)
- Space · auxiliary
- O(1)
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 1889. Minimum Space Wasted From Packaging is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 2389 | Longest Subsequence With Limited Sum | Easy |
| 2448 | Minimum Cost to Make Array Equal | Hard |
| 2602 | Minimum Operations to Make All Array Elements Equal | Medium |
| 1894 | Find the Student that Will Replace the Chalk | Medium |
| 0354 | Russian Doll Envelopes | Hard |
| 0363 | Max Sum of Rectangle No Larger Than K | Hard |
Frequently asked questions
- How hard is LeetCode 1889. Minimum Space Wasted From Packaging?
LeetCode 1889. Minimum Space Wasted From Packaging is rated Hard on LeetCode.
- What topics does LeetCode 1889. Minimum Space Wasted From Packaging cover?
LeetCode 1889. Minimum Space Wasted From Packaging is tagged Array, Binary Search, Prefix Sum and Sorting on LeetCode.