Monitoring~30 min2s · 256 MBtarget O(m³) time, O(m²) spaceclassic twin: lc-1547dp
An observability platform archives a log file of length bytes. The file must be split at marked byte offsets into separate files. Each split cuts one existing piece into two, and copying that piece costs its length in bytes.
The offsets can be used in any order, and the order changes the total copying cost. Your team lead asks: "In which order should we split the file to copy as few bytes as possible?"
Write least_split_cost(length, offsets).
length bytes, from offset 0 to offset length.offsets lists the distinct offsets, each strictly between 0 and length, in no particular order. The file must be split at every one of them.Input: length = 12, offsets = [8, 3, 5]
Output: 24Sort the offsets and add the two ends, which gives the points [0, 3, 5, 8, 12]. Let cost[i][j] be the least cost of splitting the piece from point i to point j at every point strictly between them. Choose the point k that is split first. That split copies the whole piece, points[j] - points[i], and leaves the pieces [i, k] and [k, j].
We fill by the distance j - i.
| Distance | Pieces (i, j) and their cost |
|---|---|
| 2 | (0, 2): 5, (1, 3): 5, (2, 4): 7 |
| 3 | (0, 3): 13, (1, 4): 14 |
| 4 | (0, 4): 24 |
For the whole file, k = 1, 2, 3 give 26, 24, 25. The least is 24.
Input: length = 10, offsets = [5]
Output: 10One split of the whole file costs its length, 10.
Input: length = 7, offsets = [2, 3, 4]
Output: 13Splitting at 3 first costs 7. Then the piece 0 to 3 at 2 costs 3, and the piece 3 to 7 at 4 costs 4, so the total is 14. Splitting at 4 first costs 7, then 2 costs 4, and then 3 costs 2. That is 13, the least.
2 ≤ length ≤ 1,000,0001 ≤ len(offsets) ≤ 100, with 1 ≤ offsets[i] < length, and all offsets are different.There are up to 100 factorial orders, so none can be listed. With m = len(offsets) + 2 points, a table over pieces has about m²/2 entries, and each tries up to m split points. That is 171,700 steps for 100 offsets, which is small. The length of the file, 1,000,000, only appears in the costs, never in the loops.