134. Gas Station

class Solution(object):
    def canCompleteCircuit(self, gas, cost):
        """
        :type gas: List[int]
        :type cost: List[int]
        :rtype: int
        """
        N=len(gas)
        start=0
        tank=0
        total=0
        for i in range(N):
            tank+=(gas[i]-cost[i])
            #if starting from A and encounter the first unreachable station B, shift to B+1 station to start, but accumulate the total calculated from A to B
            if tank<0:
                start=i+1
                total+=tank
                tank=0
        return start if total+tank>=0 else -1
                
      

你可能感兴趣的:(134. Gas Station)