[Algorithm] 40 week(10.31 ~ 11.04) 3/3

Dev_min·2022년 11월 2일
0

algorithm

목록 보기
131/157

134. Gas Station

var canCompleteCircuit = function(gas, cost) {
    if(sum(gas) < sum(cost)) return -1;

    let start = 0;
    let fuel = 0;

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

    return start;
};

const sum = (numbers) => {
    return numbers.reduce((acc, curr) => acc + curr, 0)
}
profile
TIL record

0개의 댓글