Parcel-delivery app~30 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-1186kadane · dp
A freight depot plans delivery tours. Every stop on a route has a margin in units: what the depot earns there minus what it costs to serve. Some stops lose money, so some margins are negative.
A tour is a run of consecutive stops from the route, served in order. The planner may also drop one stop from the run, for example a customer who cancelled. The stops on either side then stay in the tour, and the van drives straight between them.
The tour must keep at least one stop. Your team lead asks for the largest total margin that any tour can reach.
Write best_tour_margin(margins).
margins[i] is the margin of stop i, in route order.Input: margins = [5, -2, -8, 7, 3, -1, 4]
Output: 16Drop the -8. The tour is 5, -2, 7, 3, -1, 4, and its total is 16. Without a drop, the best run is 7, 3, -1, 4 with 13.
Keep two numbers for each stop.
keep_run is the best total of a run that ends here with nothing dropped.
drop_run is the best total of a run that ends here and has dropped one stop.
| Stop | Margin | keep_run |
drop_run |
Best so far |
|---|---|---|---|---|
| 0 | 5 | 5 | none | 5 |
| 1 | -2 | 3 | 5 | 5 |
| 2 | -8 | -5 | 3 | 5 |
| 3 | 7 | 7 | 10 | 10 |
| 4 | 3 | 10 | 13 | 13 |
| 5 | -1 | 9 | 12 | 13 |
| 6 | 4 | 13 | 16 | 16 |
Input: margins = [-4, -2]
Output: -2Every stop loses money. The tour must keep a stop, so the best tour is the single stop with margin -2.
Input: margins = [3, -4, 5]
Output: 8Drop the -4. The stops 3 and 5 join up and total 8. The best run with no drop is only 5.
1 ≤ length of margins ≤ 10^5-10^9 ≤ margins[i] ≤ 10^9Trying every stop as the dropped one and then searching the shorter route costs about n^2 steps at best, and about n^3 / 2 with a plain search. For 100,000 stops that is far too much.
Each stop needs only a constant amount of work. The best tour that ends at a stop depends on the tours that ended at the stop before. There are two states: nothing dropped yet, or one stop dropped.