-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathGas Station.java
More file actions
38 lines (32 loc) · 923 Bytes
/
Gas Station.java
File metadata and controls
38 lines (32 loc) · 923 Bytes
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
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int N = gas.length;
int startIndex = 0;
while (startIndex < N) {
int filled = 0;
int required = 0;
boolean found = true;
for (int i = 0; i < N; i++) {
int k = i + startIndex;
if (k >= N) {
k -= N;
}
filled += gas[k];
required += cost[k];
if (required > filled) {
found = false;
break;
}
}
if (found) {
return startIndex;
} else {
filled = 0;
required = 0;
startIndex++;
}
}
return -1;
}
}