Skip to content

Gas Station #15

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
siyuan25 opened this issue Sep 7, 2021 · 0 comments
Open

Gas Station #15

siyuan25 opened this issue Sep 7, 2021 · 0 comments

Comments

@siyuan25
Copy link
Contributor

siyuan25 commented Sep 7, 2021

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;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant