Simple Intuitive Python Solution

  • 0

    First we check whether the total amount of gas is enough for the whole trip.
    Then, starting from index 0, we keep the current remaining gas in the tank. If it drops below 0, then we can infer that from some index in the latter part of the trip we have enough gas for it. So we just keep moving the index forward and finally we can get the answer.

    class Solution(object):
        def canCompleteCircuit(self, gas, cost):
            :type gas: List[int]
            :type cost: List[int]
            :rtype: int
            if sum(gas) < sum(cost):
                return -1
            index = 0
            current = 0
            for i in range(len(gas)):
                current += gas[i]-cost[i]
                if current < 0:
                    current = 0
                    index = i+1
            return index

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.