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

Feb 23, 2025 - 16:13
 0
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;
};