Skip to content

Commit 0c65784

Browse files
committed
add: GasStations
1 parent fc12054 commit 0c65784

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

java/Greedy/GasStations.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import java.util.Arrays;
2+
3+
public class GasStations {
4+
public int gasStations(int[] gas, int[] cost) {
5+
// If the total gas is less than the total cost, completing the
6+
// circuit is impossible.
7+
if (Arrays.stream(gas).sum() < Arrays.stream(cost).sum()) {
8+
return -1;
9+
}
10+
int start, tank;
11+
start = tank = 0;
12+
for (int i = 0; i < gas.length; i++) {
13+
tank += gas[i] - cost[i];
14+
// If our tank has negative gas, we cannot continue through the
15+
// circuit from the current start point, nor from any station
16+
// before or including the current station 'i'.
17+
if (tank < 0) {
18+
// Set the next station as the new start point and reset the
19+
// tank.
20+
start = i + 1;
21+
tank = 0;
22+
}
23+
}
24+
return start;
25+
}
26+
}

0 commit comments

Comments
 (0)