-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path134. Gas Station (Leetcode) (optimized + unoptimized)
59 lines (47 loc) · 1.59 KB
/
134. Gas Station (Leetcode) (optimized + unoptimized)
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
51
52
53
54
55
56
57
58
// class Solution {
// public int canCompleteCircuit(int[] gas, int[] cost) {
// int volumeOfGas = 0;
// for(int i = 0; i < gas.length; i++) {
// volumeOfGas = gas[i];
// for(int j = ( i + gas.length + 1) % gas.length, count = 0, counter = ( i + gas.length + 1) % gas.length; count < gas.length; count++) {
// volumeOfGas = (volumeOfGas - cost[j]) + gas[j];
// if(volumeOfGas < 0) break;
// if(j == counter) return i;
// }
// }
// return -1;
// }
// }
// class Solution {
// public int canCompleteCircuit(int[] gas, int[] cost) {
// int n = gas.length;
// for (int i = 0; i < n; i++) {
// int start = i;
// int gasLeft = 0;
// while (gasLeft >= 0) {
// gasLeft = gasLeft + gas[start] - cost[start];
// start = (start + 1) % n;
// if (start == i && gasLeft >= 0) {
// return i;
// }
// }
// }
// return -1;
// }
// }
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int totalGas = 0;
int currentGas = 0;
int start = 0;
for (int i = 0; i < gas.length; i++) {
totalGas = totalGas + gas[i] - cost[i];
currentGas = currentGas + gas[i] - cost[i];
if (currentGas < 0) {
start = i + 1;
currentGas = 0;
}
}
return totalGas >= 0 ? start : -1;
}
}