DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 134. Gas Station

/**
 * @param {number[]} gas
 * @param {number[]} cost
 * @return {number}
 */
var canCompleteCircuit = function(gas, cost) {

    let gasTotal = gas.reduce((sum, num) => sum + num, 0);
    let costTotal = cost.reduce((sum, num) => sum + num, 0);
    let n = gas.length;
    if(gasTotal < costTotal){
        return -1 ; 
    }
    let total = 0 ; 
    let res = 0  ; 
    for(let i = 0 ; i < n ; i++){

        total+= gas[i]-cost[i];

        if(total<0){
            total = 0 ;
            res =  i + 1;
        }
    }
    return res;
}; 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)