Gas station
If the total petrol is less than the total distance, no start works. Otherwise there is a start: run through the pumps with a tank; whenever the tank drops below zero, no pump from the current start up to here can be the start, so restart just after it.
How to recognise it
- A circular route with gains and costs at each stop.
- Find a starting point from which a running total never goes negative.
- One pass instead of trying every start.
One pass
start = 0; tank = 0; total = 0
for i:
gain = petrol[i] - distance[i]
total += gain; tank += gain
if tank < 0: start = i + 1; tank = 0
return total < 0 ? -1 : start
| pump | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| gain | -2 | 1 | 4 | -1 |
| tank | -2, restart | 1 | 5 | 4 |
The total gain is 2, so start 1 works.
Common mistakes
- Trying every start: O(n²).
- Forgetting the total check, which is what makes the single pass correct.
Problems
- Find the first circular tour that visits all Petrol Pumpsmediumguide ready