class Solution(object): def canCompleteCircuit(self, gas, cost): """ :type gas: List[int] :type cost: List[int] :rtype: int """ n = len(gas) if (sum(gas) - sum(cost)) < 0: # if total gas at all stations is less than total cost , then no soln. exists return -1 tank = 0 src = 0 # starting from index 0 cur = 0 while True: tank += gas[cur] # car is at 'cur', fill the tank if tank - cost[cur] < 0: # car can't move to next stop, let car begin from next stop tank = 0 # empty the tank src = (cur+1)%n # update src cur = src # move to src continue # move back to start of the loop tank -= cost[cur] # moving to next emptied the gas by cost[cur] cur = (cur +1)%n # reached next if src == cur: # did complete cycle? return src # return start
Very simple python logic
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.