1
2
3
4
5
[0][1][2][3][4]
cost
3
4
5
1
2
[0][1][2][3][4]
Greedy · one pass, reset start past each failure
▸1given gas, cost2total ← 0; tank ← 0; start ← 03for i ← 0 to n − 1:4 d ← gas[i] − cost[i]5 total += d; tank += d6 if tank < 0: // segment start..i unusable7 start ← i + 1; tank ← 08return total ≥ 0 ? start : −1
state
- gas[1, 2, 3, 4, 5]
- cost[3, 4, 5, 1, 2]