Minimum Space Wasted From Packaging — LeetCode 1889 Python Solution
HardArrayBinary SearchPrefix SumSorting
- Problem
- #1889
- Pattern
- Prefix Sum
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(log n) or O(n log n) |
| Space | O(1) auxiliary |
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
LeetCode 2389Longest Subsequence With Limited SumEasyLeetCode 2448Minimum Cost to Make Array EqualHardLeetCode 2602Minimum Operations to Make All Array Elements EqualMediumLeetCode 1894Find the Student that Will Replace the ChalkMediumLeetCode 354Russian Doll EnvelopesHardLeetCode 363Max Sum of Rectangle No Larger Than KHard
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.