Leetcode Daily Problem - 7 Jan 2023

Leetcode Daily Problem - 7 Jan 2023

Gas Station

Problem Name - Gas Station

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

Solution 1

/**
 * @param {number[]} gas
 * @param {number[]} cost
 * @return {number}
 */
var canCompleteCircuit = function(gas, cost) {
    const sum1 = gas.reduce((total, num) => total + num);
    const sum2 = cost.reduce((total, num) => total + num);

    if(sum1 < sum2) {
        return -1;
    }

    let index = 0;
    let curr = 0;
    for(let i=0;i<gas.length;i++){
        curr += gas[i] - cost[i];
        if(curr<0){
            curr = 0;
            index = i+1;
        }
    }

    return index;
};