There are
n
gas stations along a circular route, where the amount of gas at theith
station isgas[i]
.You have a car with an unlimited gas tank and it costs
cost[i]
of gas to travel from theith
station to its next(i + 1)th
station. You begin the journey with an empty tank at one of the gas stations.Given two integer arrays
gas
andcost
, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return-1
. If there exists a solution, it is guaranteed to be unique.
class Solution:
def canCompleteCircuit(self, gas, cost):
# 记录总 gas 能不能支持全部旅程、当前 gas、起始站
total = 0
in_tank = 0
start = 0
for i in range(len(gas)):
total += gas[i] - cost[i]
in_tank += gas[i] - cost[i]
# 重置起点位置
if in_tank < 0:
start = i + 1
in_tank = 0
return start if total >= 0 else -1