Gas Station Problem

Problem Description

Solution Explanation

Implementation

class Solution:

    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:

        if sum(gas)<sum(cost):

            return -1

        total = 0

        starting_position = 0

        for i in range(len(gas)):

            total += (gas[i] - cost[i])

            if total < 0:

                total = 0

                starting_position = i + 1 # switch to the next starting pos

        return starting_position