Parcel-delivery app~20 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-1167heaps
A parcel-delivery depot ties straps together to make one long strap for a large load. The straps have different lengths, in centimetres.
A worker joins two straps with one knot, and the knot takes as many seconds as the two lengths added together. The new strap is as long as both. The worker repeats this until one strap is left.
Your team lead says: "Plan the knots so the total time is as small as possible." A depot can hold 100,000 straps.
Write least_knotting_time(lengths).
lengths[i] is the length of strap i.int.Input: lengths = [7, 2, 9, 4, 5]
Output: 60Keep the straps in a min-heap. Take the two shortest, knot them, and put the new strap back in the heap.
| Knot | Two shortest | Time | Straps in the heap afterwards |
|---|---|---|---|
| 1 | 2 and 4 | 6 | 5, 6, 7, 9 |
| 2 | 5 and 6 | 11 | 7, 9, 11 |
| 3 | 7 and 9 | 16 | 11, 16 |
| 4 | 11 and 16 | 27 | 27 |
The total time is 6 + 11 + 16 + 27 = 60.
Input: lengths = [1, 1, 1, 1]
Output: 8Knot 1 and 1 twice, for 2 seconds each. Then knot the two straps of length 2, for 4 seconds. The total is 8.
Input: lengths = [3]
Output: 0One strap needs no knot.
1 ≤ length of lengths ≤ 10^51 ≤ lengths[i] ≤ 10^6Scanning the list for the two shortest straps after every knot costs about n steps, and there are n - 1 knots. For n = 100,000 that is about 5 × 10^9 steps.
A min-heap gives the two shortest straps in about log n steps each. Ten to the five straps of length 10^6 give a total near 1.7 × 10^12, so the answer needs a 64-bit integer.