Practice problem · easy
A returns centre in a delivery warehouse has a pressing machine. The machine takes the two heaviest parcels from the pile and presses them together, and the pile changes after every press.
You work on the machine's control software. A pile can hold up to 100,000 parcels, so the machine must find the two heaviest quickly, again and again.
Write last_parcel(weights).
weights[i] is the weight of parcel i.0 when none is left.Input: weights = [2, 7, 4, 1, 8, 1]
Output: 1| Round | Two heaviest | What stays | Pile after |
|---|---|---|---|
| 1 | 8 and 7 | 1 | 2, 4, 1, 1, 1 |
| 2 | 4 and 2 | 2 | 1, 1, 1, 2 |
| 3 | 2 and 1 | 1 | 1, 1, 1 |
| 4 | 1 and 1 | nothing | 1 |
One parcel is left, with weight 1.
Input: weights = [5, 5]
Output: 0The two parcels weigh the same, so both are gone and nothing is left.
Input: weights = [3]
Output: 3A single parcel is already the last one.
1 ≤ length of weights ≤ 10^51 ≤ weights[i] ≤ 10^6A pile of 100,000 parcels needs up to 99,999 rounds. If each round sorted the whole pile, the machine would do about 100,000 sorts of 100,000 parcels each, which is far too slow.
You only need the two heaviest parcels each round. A structure that keeps the largest item on top, and fixes itself in about 17 steps after each change, fits the job.
last_parcel · runs in your browserCoding is easiest on a laptop. On a phone, read, trace and try small edits.