Created
September 30, 2020 21:15
-
-
Save Robogeek95/a438bac58ac065293df9f3875a5d3db4 to your computer and use it in GitHub Desktop.
gasstation.cpp https://leetcode.com/problems/gas-station/ | my solution in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[]} gas | |
* @param {number[]} cost | |
* @return {number} | |
*/ | |
var canCompleteCircuit = function(gas, cost) { | |
let start=0, gasLeft=0, sum=0; // left-gas left in the tank | |
for (let i=0; i<gas.length; i++) { | |
gasLeft+= gas[i] - cost[i]; | |
sum+= gas[i] - cost[i]; | |
if (sum<0) { | |
sum=0; | |
start=i+1; | |
} | |
} | |
return gasLeft<0 ? -1: start; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment