python-leetcode-加油站
134. 加油站 - 力扣(LeetCode)
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
n = len(gas)
total_gas = 0
total_cost = 0
start = 0
tank = 0
for i in range(n):
total_gas += gas[i]
total_cost += cost[i]
tank += gas[i] - cost[i]
# 如果当前油箱小于0,从下一个加油站重新开始
if tank < 0:
start = i + 1
tank = 0
# 如果总汽油量大于等于总消耗量,则返回起点,否则返回 -1
return start if total_gas >= total_cost else -1