Maps app~45 min2s · 256 MBtarget O(n) time, O(n) spacedp
A maps team sends survey crews along one straight road. Point i is at the distance marks[i] from the depot, and the marks are sorted from the nearest point to the farthest.
Each crew trip serves a block of consecutive points. A trip costs a fixed fee plus the square of the distance between its first and last point, because a long trip tires the crew more. Your team lead asks: "How do we group the points so that the total cost is smallest?" A day can have 100,000 points.
Write min_dispatch_cost(marks, fee).
marks[i] is the distance of point i from the depot. The marks are in non-decreasing order, and two points can wait at the same mark.a to point b costs fee + (marks[b] - marks[a])².Input: marks = [1, 2, 3, 10, 11], fee = 8
Output: 21Let dp[i] be the least cost for the first i points. The best last block for each i:
| Points served | Best last block (marks) | Block cost | Total |
|---|---|---|---|
| 1 | 1 | 8 | 8 |
| 2 | 1, 2 | 9 | 9 |
| 3 | 1, 2, 3 | 12 | 12 |
| 4 | 10 | 8 | 20 |
| 5 | 10, 11 | 9 | 21 |
One trip for the marks 1, 2 and 3 costs 8 + 4 = 12. One trip for the marks 10 and 11 costs 8 + 1 = 9. The total is 21.
Input: marks = [0, 10, 20], fee = 50
Output: 150Three trips of one point cost 50 each. Joining any two points adds a squared distance of at least 100 and saves only 50.
Input: marks = [5], fee = 3
Output: 3One point needs one trip, with a span of zero.
1 ≤ len(marks) ≤ 100,0000 ≤ marks[i] ≤ 100,000, and marks never decreases0 ≤ fee ≤ 1,000,000The table has 100,000 entries. Each entry looks at every earlier entry, so the work is about 5 billion steps. That is far beyond a 2-second limit. Each entry must find its best earlier entry without looking at all of them.