Created
September 30, 2020 20:25
-
-
Save dabsclement/92a1cd465a43c97ec18afd1de1aa9650 to your computer and use it in GitHub Desktop.
LeetCode gas station
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) { | |
if(gas.length==0){ | |
return -1; | |
} | |
if(gas.length==1){ | |
return gas[0]-cost[0]<0?-1:0; | |
} | |
let start = 0; | |
let end = 1; | |
let curr= gas[0]-cost[0]; | |
while(start!=end) { | |
while(curr<0 && start!=end) { | |
curr= curr- (gas[start]-cost[start]); | |
start = (start+1)%gas.length; | |
if(start==0) | |
return -1; | |
} | |
curr+= gas[end]-cost[end]; | |
end = (end+1)%gas.length; | |
} | |
if(curr<0) | |
return -1; | |
return start; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment