Skip to content

Instantly share code, notes, and snippets.

@Robogeek95
Created September 30, 2020 21:15
Show Gist options
  • Save Robogeek95/a438bac58ac065293df9f3875a5d3db4 to your computer and use it in GitHub Desktop.
Save Robogeek95/a438bac58ac065293df9f3875a5d3db4 to your computer and use it in GitHub Desktop.
gasstation.cpp https://leetcode.com/problems/gas-station/ | my solution in javascript
/**
* @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