Tram loop express
MediumOnline Assessment
Plan the most profitable morning run of a tram on a circular line, when it may run express through one stop.
The line is a loop of n stops numbered 0 to n - 1 in the order the trams travel; after stop n - 1 comes stop 0 again. The string boardings has one digit per stop: boardings[i] is how many passengers (in tens) board at stop i. Every stop at which the tram actually stops costs stop_cost (the same for every stop), so serving stop i earns int(boardings[i]) - stop_cost, which can be negative.
A run starts at any stop and then visits consecutive stops in travel order. It never visits a stop twice, so it covers at most n stops and may cross from stop n - 1 back to stop 0. During the run the driver may run express through at most one stop: that stop is passed without stopping, earning nothing and costing nothing. Every other stop of the run is served. A run must serve at least one stop.
Find the largest total earnings any run can achieve.
Input: boardings, a string of n digits (n >= 1); stop_cost, an integer between 0 and 9.
Output: the maximum total earnings, as an integer (it is negative when every stop loses money, because the run still has to serve one stop).
Example 1
- Input:
- ["91827",4]
- Output:
- 12
- Explanation
- With cost 4 the stops earn 5, -3, 4, -2, 3. The best run starts at stop 4, wraps to stops 0 and 1, and goes on to stop 2, running express through the loss-making stop 1: it serves 3 + 5 + 4 = 12. Serving stop 1 as well would only give 9, and the full loop (all five stops) with one express is at most 10.
Example 2
- Input:
- ["3112",5]
- Output:
- -2
- Explanation
- Every stop loses money (-2, -4, -4, -3), but a run has to serve at least one stop and cannot run express through its only stop. The best choice is to serve just stop 0, for -2.
Example 3
- Input:
- ["9090",3]
- Output:
- 12
- Explanation
- With cost 3 the stops earn 6, -3, 6, -3. Going around the loop twice is not allowed: the run starting at stop 0 serves stops 0 and 2, with stop 1 express, for 12. Using all four stops with one express gives only 9.
Constraints
1 <= n <= 9000, wherenis the length ofboardingsboardingscontains only the digits0to90 <= stop_cost <= 9