-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path0134-gas-station.js
More file actions
50 lines (42 loc) · 1.23 KB
/
0134-gas-station.js
File metadata and controls
50 lines (42 loc) · 1.23 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* https://leetcode.com/problems/gas-station/
* Time: O(n)
* @param {number[]} gas
* @param {number[]} cost
* @return {number}
*/
var canCompleteCircuit = function (gas, cost) {
let netDistance = 0;
let res = 0;
//Checks if theres enough gas to complete a cycle
if (gas.reduce((a, b) => a + b) - cost.reduce((a, b) => a + b) < 0)
return -1;
// Finds the first appearence of a positive netDistance, if the cycle can't
// be completed (netDistance < 0), starts cycle again @ the next positive netDistance value.
for (let i = 0; i < gas.length; i++) {
netDistance += gas[i] - cost[i];
if (netDistance < 0) {
netDistance = 0;
res = i + 1;
}
}
return res;
};
/**
* @param {number[]} gas
* @param {number[]} cost
* @return {number}
*/
var canCompleteCircuit = function (gas, cost) {
let [totalTank, currTank, startingStation] = [0, 0, 0];
for (let i = 0; i < gas.length; i++) {
totalTank += gas[i] - cost[i];
currTank += gas[i] - cost[i];
const isEmpty = currTank < 0;
if (isEmpty) {
startingStation = i + 1;
currTank = 0;
}
}
return 0 <= totalTank ? startingStation : -1;
};