Bank app~45 min2s · 256 MBtarget O(n²) time, O(n²) spacedp
A bank stores its ledger as n shards, side by side in date order. Shard i holds sizes[i] entries. A compaction step merges two neighbouring shards into one, and it rewrites every entry of both shards.
The cost of a step is the number of entries it rewrites. Compaction goes on until one shard remains. Your team lead asks: "In which order do we merge so that the total rewrite is smallest?" A ledger can have 1,500 shards.
Write min_compaction_cost(sizes).
sizes[i] is the number of entries in shard i, in date order.0 when there is only one shard.Input: sizes = [3, 1, 4, 2]
Output: 20With four shards there are five merge orders. In each, the last step costs 10, the size of everything:
| Merge order | Step costs | Total |
|---|---|---|
| (3 (1 (4 2))) | 6 + 7 + 10 | 23 |
| (3 ((1 4) 2)) | 5 + 7 + 10 | 22 |
| ((3 1) (4 2)) | 4 + 6 + 10 | 20 |
| ((3 (1 4)) 2) | 5 + 9 + 10 | 23 |
| (((3 1) 4) 2) | 4 + 8 + 10 | 22 |
The best order merges the first two shards and the last two shards, and then the two results.
Input: sizes = [5, 5]
Output: 10One step makes a shard of size 10.
Input: sizes = [9]
Output: 0There is only one shard, so nothing is merged.
1 ≤ len(sizes) ≤ 1,5001 ≤ sizes[i] ≤ 1,000A table with one entry for each range of shards has about 1.1 million entries. Filling an entry by trying every last split costs up to 1,500 steps, so the whole table needs about 560 million steps. That is too slow for 2 seconds. Each entry must try far fewer splits.