Gas Station Leetcode Python


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.
Note:
The solution is guaranteed to be unique.
まず総油が足りないと判断し、総油が総消費より小さいと歩ききれないに違いない.次に、プロセス中に残った油が0未満になるかどうかを判断し、0未満であれば次のstationから開始するしかない.一度遍歴すれば答えが得られる.
1. compare total gas and total cost, if             total gasreturn -1
2. iterate the whole station, rest+=gas[i]-cost[i] if rest<0, search start from the next i
return station
class Solution:
    # @param gas, a list of integers
    # @param cost, a list of integers
    # @return an integer
    def canCompleteCircuit(self, gas, cost):
        if sum(gas)<sum(cost):
            return -1
        else:
            pre=0
            rest=0
            station=0
            for index in range(len(gas)):
                rest+=gas[index]-cost[index]
                if rest<0:
                    pre+=rest
                    rest=0
                    station=index+1
        return station