Parcel-delivery app~45 min2s · 256 MBtarget O(k × n log n) time, O(n) spacedivide-and-conquer
A freight team plans one delivery route with n stops in a fixed order. Stop i has loads[i] parcels. The route is driven in k shifts. Each shift covers a block of consecutive stops, and every shift covers at least one stop.
The strain of a shift is the square of the parcels in its block, because one heavy shift tires a driver far more than two light ones. Your team lead asks: "Where do we cut the route so that the total strain is smallest?" A route can have 5,000 stops and up to 30 shifts.
Write min_total_strain(loads, k).
loads[i] is the number of parcels at stop i, in route order.k blocks of consecutive stops. Every block has at least one stop.k blocks.Input: loads = [3, 1, 4, 1, 5], k = 2
Output: 100With two shifts there is one cut, and it can fall after any of the first four stops. The strain of each choice:
| Cut after stop | Shift 1 load | Shift 2 load | Total strain |
|---|---|---|---|
| 1 | 3 | 11 | 130 |
| 2 | 4 | 10 | 116 |
| 3 | 8 | 6 | 100 |
| 4 | 9 | 5 | 106 |
The best cut is after stop 3, with loads 8 and 6, so the total strain is 64 + 36 = 100.
Input: loads = [5, 5, 5, 5], k = 2
Output: 200Two shifts of load 10 give 100 + 100.
Input: loads = [7], k = 1
Output: 49One stop and one shift: the strain is 7 squared.
1 ≤ len(loads) ≤ 5,0001 ≤ loads[i] ≤ 1,0001 ≤ k ≤ 30 and k ≤ len(loads)The usual table has one entry for each pair of a stop count and a shift count, which is about 150,000 entries. Filling one entry by trying every cut point costs up to 5,000 steps, so the whole table needs about 370 million steps. That is too slow here. The answer must come from fewer cut points for each entry.