Minimum Space Wasted From Packaging LeetCode solution in Python
1# Runtime: 2545 ms (Top 38.89%) | Memory: 37.8 MB (Top 95.24%)2class Solution:3def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int:4# prefix sum to save time5acc = [0] + [*accumulate(packages)]6packages.sort()78ans = float("inf")9for box in boxes:10tmp = 011# deal with smallest box first12box.sort()1314# record number of packages already dealt with15start = 01617for b in box:18loc = bisect.bisect(packages, b)19if loc == 0:20continue21tmp += b * (loc - start) - (acc[loc] - acc[start])2223# all are packaged24if loc == len(packages):25ans = min(ans, tmp)26break2728start = loc2930return ans % (10**9 + 7) if ans != float("inf") else -1