#1889
Minimum Space Wasted From Packaging
HardArrayBinary SearchSortingPrefix SumSortingPrefix Sum
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n + m log m + m * k), where n is the number of packages, m is the number of suppliers, and k is the average number of boxes per supplier. |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n + m log m + m * k), where n is the number of packages, m is the number of suppliers, and k is the average number of boxes per supplier.Space O(n)
This approach uses sorting and binary search to efficiently find the best fitting boxes for packages, minimizing wasted space. By leveraging prefix sums, we can quickly calculate total waste for each supplier.
⚙️
Algorithm
5 steps- 1Step 1: Sort the packages array.
- 2Step 2: For each supplier's box sizes, sort the box sizes.
- 3Step 3: If the largest box size is less than the largest package, skip this supplier.
- 4Step 4: Use a prefix sum array to calculate the total size of packages up to each index.
- 5Step 5: For each box size, use binary search to find how many packages can fit and calculate the waste using the prefix sum.
solution.py20 lines
1def minWastedSpace(packages, boxes):
2 packages.sort()
3 prefix_sum = [0] * (len(packages) + 1)
4 for i in range(len(packages)):
5 prefix_sum[i + 1] = prefix_sum[i] + packages[i]
6 min_waste = float('inf')
7 for box_sizes in boxes:
8 box_sizes.sort()
9 if box_sizes[-1] < packages[-1]:
10 continue
11 waste = 0
12 j = 0
13 for box in box_sizes:
14 count = 0
15 while j < len(packages) and packages[j] <= box:
16 j += 1
17 waste += (j - count) * box - (prefix_sum[j] - prefix_sum[count])
18 count = j
19 min_waste = min(min_waste, waste)
20 return min_waste if min_waste != float('inf') else -1ℹ
Complexity note: The complexity is dominated by the sorting of packages and boxes, and the prefix sum array takes linear space.
- 1Sorting the packages and box sizes allows for efficient fitting and waste calculation.
- 2Using prefix sums helps in quickly calculating the total size of packages that fit into boxes.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.