-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGas.java
More file actions
39 lines (38 loc) · 1018 Bytes
/
Gas.java
File metadata and controls
39 lines (38 loc) · 1018 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
39
package algorithm.array;
public class Gas {
public static void main(String[] args) {
int[] gas = new int[]{2,3,4};
int[] cost = new int[]{3,4,3};
int res = test(gas, cost);
System.out.println("res = " + res);
}
public static int test(int[] gas, int[] cost) {
int b = -1;
for (int x = 0; x < gas.length; x++) {
if (gas[x] < cost[x]) {
continue;
}
b = x;
int g = 0;
while (g + gas[x] - cost[x] >= 0) {
g = g + gas[x] - cost[x];
x++;
x = x % gas.length;
if (x == b) {
return b;
}
}
if (x < b) {
return -1;
}
if (g + gas[x] - cost[x] < 0) {
if (x == b) {
return -1;
} else {
x--;
}
}
}
return -1;
}
}