DEV Community

Debesh P.
Debesh P.

Posted on • Edited on

134. Gas Station | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/gas-station/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/gas-station/solutions/7439501/most-optimal-approach-explanation-with-d-es79


leetcode 134


Solution

class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int totalGas = 0;
        int totalCost = 0;

        for(int i=0; i<gas.length; i++) {
            totalGas += gas[i];
            totalCost += cost[i];
        }

        if(totalGas < totalCost) {
            return -1;
        }

        int currGas = 0;
        int startIndex = 0;

        for(int i=0; i<gas.length; i++) {
            currGas += gas[i] - cost[i];

            if(currGas < 0) {
                startIndex = i + 1;
                currGas = 0;
            }
        }

        return startIndex;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)