Why it matters

Gas station is classic greedy trick. Understanding shapes technique.

Advertisement

The architecture

Track cumulative balance.

When negative, restart at next.

Total balance >= 0 means solvable.

Gas station greedyCumulative balancegas - costReset on negativenext stationTotal non-negativesolvableIf total gas >= total cost, solution exists; else impossible
Gas station.
Advertisement

How it works end to end

If total sum negative: impossible.

Reset start on negative running balance.

O(n) single pass.