Ride-hailing app~40 min2s · 256 MBtarget O(n^3 / (k - 1)) time, O(n^2) spaceclassic twin: lc-1000dp
A ride-hailing platform writes a trip log shard for each hour of a day. Before the nightly audit, the shards must be merged into one file. The merge tool takes exactly k neighbouring shards, in order, and writes one new shard.
Writing a shard costs time in proportion to its size, and the new shard is as big as the shards it replaced together. Find the cheapest way to end with one shard, or say it cannot be done.
Write merge_cost(sizes, k).
sizes[i] is the size of shard i, and the shards are in order along a list.k neighbouring shards and replaces them by one shard. Its cost, and its size, is the total size of the shards it replaced.-1 if that is not possible.Input: sizes = [3, 2, 4, 1], k = 2
Output: 20Let cost[i][j] be the cheapest cost of merging shards i to j down to as few shards as possible. Here k = 2, so every run can become one shard.
| Run | Best split | Cost of the parts | Total of the run | cost[i][j] |
|---|---|---|---|---|
| 0 to 1 | 3 and 2 | 0 | 5 | 5 |
| 1 to 2 | 2 and 4 | 0 | 6 | 6 |
| 2 to 3 | 4 and 1 | 0 | 5 | 5 |
| 0 to 2 | (3 and 2) with 4 | 5 | 9 | 14 |
| 1 to 3 | 2 with (4 and 1) | 5 | 7 | 12 |
| 0 to 3 | (3 and 2) with (4 and 1) | 10 | 10 | 20 |
The best order merges 3 and 2 (cost 5), then 4 and 1 (cost 5), then the two results (cost 10).
Input: sizes = [3, 5, 1, 2, 6], k = 3
Output: 25Merge 5, 1 and 2 first (cost 8), giving [3, 8, 6], then merge all three (cost 17). The total is 25.
Input: sizes = [3, 5, 1, 2, 6], k = 4
Output: -1A merge of 4 shards leaves 5 − 3 = 2 shards, and a second merge needs 4. So one shard can never be reached.
1 ≤ len(sizes) ≤ 100 and 1 ≤ sizes[i] ≤ 10,0002 ≤ k ≤ 100The number of merge orders grows very fast. For 100 shards merged two at a time there are more orders than atoms in the universe, so trying them all is impossible.
A table of runs has about n × n / 2 = 5,000 entries, and each entry tries up to 99 split points. That is under 200,000 steps, so a cubic method is fine.