-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathGas Station.js
32 lines (30 loc) · 978 Bytes
/
Gas Station.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Runtime: 2034 ms (Top 8.12%) | Memory: 50.3 MB (Top 81.93%)
var canCompleteCircuit = function(gas, cost) {
const len = gas.length;
// scan forward from the current index
const scan = (i) => {
let numTries = 0;
let tank = 0;
let c = 0;
while (numTries <= len) {
tank -= c;
if (tank < 0) return -1;
// if we made it back around, and we have gas, return the index, we made it!
if (numTries === len && tank >= 0) {
return i;
}
tank += gas[i];
c = cost[i];
i++;
if (i === len) i = 0; // if we hit the end, bounce back to zero
numTries++;
}
return -1;
}
for (let i = 0; i < len; i++) {
if (!gas[i]) continue; // no gas / zero gas so let's just move on
let index = scan(i);
if (~index) return index; // if it's not -1, return it
}
return -1;
};