Learn / Greedy

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
pump0123
gain-214-1
tank-2, restart154

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

0 of 1 solved

Check yourself

Petrol [4, 6, 7, 4], distance [6, 5, 3, 5]. Which start works?

If the tank goes negative at pump i, why can no pump between the start and i be the start?

When is the answer -1?