Ride-hailing app~18 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-918kadane
A ride-hailing app runs a night loop that visits n stops in a ring, so after the last stop the bus comes back to the first. Each stop has a net value in units: fares collected minus the cost of the detour. Some stops lose money.
A driver works one shift on a block of consecutive stops. The block can start anywhere and wrap past the last stop to the first. It covers each stop at most once, and at least one stop.
Write best_shift_total(stops).
stops[i] is the net value of stop i, in units. It can be negative or zero.n - 1 is followed by stop 0.n consecutive stops on the ring, and it may wrap. Return the largest total value of any shift.Input: stops = [6, -9, 2, -4, 7, 3]
Output: 16The best shift starts at stop 4 and wraps: 7 + 3 + 6 = 16.
Track the best run and the worst run inside the row, and the total.
| Stop | Value | best_here | best_so_far | worst_here | worst_so_far | total |
|---|---|---|---|---|---|---|
| 0 | 6 | 6 | 6 | 6 | 6 | 6 |
| 1 | -9 | -3 | 6 | -9 | -9 | -3 |
| 2 | 2 | 2 | 6 | -7 | -9 | -1 |
| 3 | -4 | -2 | 6 | -11 | -11 | -5 |
| 4 | 7 | 7 | 7 | -4 | -11 | 2 |
| 5 | 3 | 10 | 10 | -1 | -11 | 5 |
The best run inside the row is 10. A wrapping shift is the rest of the ring after the worst run: 5 - (-11) = 16. The answer is the larger, 16.
Input: stops = [-3, -1, -2]
Output: -1Every stop loses money, so the best shift is the single stop with -1.
Input: stops = [4]
Output: 4A ring of one stop has one shift.
1 ≤ stops.length ≤ 100,000 (stops on the loop)-1,000,000 ≤ stops[i] ≤ 1,000,000 (net value in units)Trying every start stop and every length costs about n × n = 10^10 additions at n = 100,000. A single pass costs about n steps. The totals reach 10^11, so use 64-bit integers.