My Python Solution


  • 0
    L

    Can we call this greedy?

    def canCompleteCircuit(self, gas, cost):
    
        if sum(gas)<sum(cost):
            return -1
        
        possible = range(len(gas))
        while len(possible) > 1:
            idx = 0
            while idx < len(possible):
                i_this = possible[idx]
                i_next = possible[(idx+1)%len(possible)]
                if gas[i_this] >= cost[i_this]:
                    gas[i_this] += gas[i_next]
                    cost[i_this] += cost[i_next]
                    del possible[(idx+1)%len(possible)]
                idx += 1
        
        return possible[0]

Log in to reply
 

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