Parcel-delivery app~15 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-1710greedy · sorting
You work on a parcel-delivery app. A depot has boxes of several types. Every box of one type holds the same number of units of goods, and the depot has a known number of boxes of each type.
A truck has room for a fixed number of boxes, whatever their type. Your team lead asks: "Which boxes do we load so that the truck carries as many units as possible?"
Write most_units_loaded(box_types, capacity).
box_types[i] is a pair [count, units]: the depot has count boxes of type i, and each holds units units.capacity boxes in all.count.Input: box_types = [[3, 4], [1, 10], [2, 6]], capacity = 4
Output: 26Sort the types by units per box, the largest first: [1, 10], [2, 6], [3, 4]. Load from the top of that list until the truck is full.
| Type | Room before | Boxes taken | Units added | Total | Room after |
|---|---|---|---|---|---|
[1, 10] |
4 | 1 | 10 | 10 | 3 |
[2, 6] |
3 | 2 | 12 | 22 | 1 |
[3, 4] |
1 | 1 | 4 | 26 | 0 |
The truck is full after the third type, so it carries 26 units.
Input: box_types = [[2, 5], [2, 3]], capacity = 10
Output: 16The depot has only 4 boxes, so every box is loaded: 2 x 5 + 2 x 3 = 16.
Input: box_types = [[5, 1], [1, 9]], capacity = 2
Output: 10The type with 5 boxes is the largest, but its boxes hold 1 unit each. Take the single box of 9 units and one box of 1 unit: 10.
1 ≤ len(box_types) ≤ 100,000, and each pair has two numbers1 ≤ count, units ≤ 10,0001 ≤ capacity ≤ 1,000,000,000There can be 100,000 box types, each with up to 10,000 boxes. Loading one box at a time while searching all types for the best one would take about 10^9 boxes times 10^5 types. A sort costs about 1.7 million steps and one pass over the types costs 100,000 more. The total can reach 10^13 units, so use a 64-bit number.