There are N gas stations along a circular route, where the amount of gas at station i is gas[i]
.
You have a car with an unlimited gas tank and it costs cost[i]
of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around the circuit once, otherwise return -1
题意:一个环路中有N个加油站,每个加油站有gap[i]的汽油,从加油站i到i+1耗油为cost[i],问一个油箱为无限大的汽车,能不能走完全程,能的话起点在哪
思路:如果环路中gas的总量比cost的总量多,那么肯定有一种方法可以让汽车跑完全程,首先什么情况下汽车不能跑完全程?比如从i出发到i+n时候,邮箱变为负值了,那么就可以把从i到i+n的节点全部滤掉
做法和求最大子列和一样
1 class Solution(object): 2 def canCompleteCircuit(self, gas, cost): 3 if not len(gas) or not len(cost) or sum(gas)<sum(cost): 4 return -1 5 balance,p= 0,0 6 for i in range(len(gas)): 7 balance += gas[i]-cost[i] 8 if balance < 0: 9 balance = 0 10 p = i+1 11 return p