Gas Station

贪心的题,感觉也说不出什么道理,只要数组里面有任何一个点能在油大于等于0的情况下走到最后这个点就是答案,如果不行得话,那它之前走过的所有点都不可能满足这个条件(证明?)

class Solution(object):
    def canCompleteCircuit(self, gas, cost):
        """
        :type gas: List[int]
        :type cost: List[int]
        :rtype: int
        """
        n = len(gas)
        result = 0
        cumGas = 0

        tmp = [gas[i] - cost[i] for i in xrange(n)]
        if sum(tmp) < 0:
            return -1

        for i in xrange(n):
            cumGas += tmp[i]
            if cumGas < 0:
                result  = i + 1
                cumGas = 0

        if result < n:
            return result
        else:
            return -1 if cumGas < 0 else result - 1

results matching ""

    No results matching ""