We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent fc12054 commit 0c65784Copy full SHA for 0c65784
java/Greedy/GasStations.java
@@ -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