美文网首页
134. Gas Station

134. Gas Station

作者: 阿团相信梦想都能实现 | 来源:发表于2016-12-16 13:49 被阅读0次
    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

          本文链接:https://www.haomeiwen.com/subject/xaunmttx.html