Problem Description
Given an array of package sizes and multiple suppliers each providing boxes of various sizes, you are required to pack each package into a box (one package per box). A package can only fit into a box if its size is less than or equal to the box’s size. For each package in a box the wasted space is (box size - package size). You must choose a single supplier and minimize the total wasted space. If it is impossible to fit all packages using one supplier’s boxes, return -1. Since the answer may be large, return it modulo 10^9 + 7.
Key Insights
- Sort the package sizes to enable efficient grouping.
- Compute a prefix sum on the sorted packages to quickly calculate the sum of values in any interval.
- For each supplier, sort their list of box sizes.
- Use binary search to identify the range of packages that can fit into a given box size.
- Accumulate wasted space by choosing for each box size the maximum possible packages that can be packed without overlaps.
- Track the minimum wasted space across all suppliers that can cover every package.
Space and Time Complexity
Time Complexity: O(n log n + Σ(boxes_j log n)) where n is the number of packages and the sum is taken over all suppliers’ boxes. Space Complexity: O(n) for sorting the packages and computing the prefix sum.
Solution
The solution begins by sorting the array of packages and computing its prefix sum to efficiently calculate the total package sizes in any interval. For each supplier, sort their available box sizes. Then, for each box size offered by the supplier, greedily pack as many of the remaining packages as possible using binary search to find the furthest package that fits. For every subset of packages assigned to a box size, the wasted space is computed as (number of packages in the group) multiplied by the box size minus the sum of the package sizes in that group. If at the end a supplier is found that can pack all packages, update the global minimum wasted space, otherwise ignore that supplier. Finally, return the minimum waste modulo 10^9 + 7, or -1 if no supplier can pack all packages.