Skip to content

Gas Station

01 · Question

There are n gas stations. You have two integer arrays gas and cost. Return the starting gas station index if you can travel around the circuit once, otherwise return -1.

02 · Solution

Reference solution

1def canCompleteCircuit(gas: List[int], cost: List[int]) -> int:
2 if sum(gas) < sum(cost):
3 return -1
4
5 start = 0
6 tank = 0
7 for i in range(len(gas)):
8 tank += gas[i] - cost[i]
9 if tank < 0:
10 start = i + 1
11 tank = 0
12 return start