cheatsheet1999/FrontEndCollection

Gas Station

siyuan25 opened this issue · 0 comments

There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.

Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique

262351630992022_ pic_hd

/**
 * @param {number[]} gas
 * @param {number[]} cost
 * @return {number}
 */
//其实是看totaltank里的油够不够开一圈
//curTank看现在的油是多少,只要不是负数就证明油够,就不加pos了,油不够就去下一个pos看看
//
var canCompleteCircuit = function(gas, cost) {
    let curTank = 0, totalTank = 0, pos = 0;
    for (let i=0;i<gas.length;i++) {
        curTank+= gas[i] - cost[i];
    //totalTank cannot depend on curTank, because curTank may become negative, //and total will be affected.
    //if solution existed, totalTank always larger than 0
        totalTank+= gas[i] - cost[i];
        if (curTank<0) {
            curTank = 0;
            pos = i+1;
        }
    }   
    return totalTank<0?-1:pos;
};