MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / GasStations

Class GasStations

java/Greedy/GasStations.java:3–26  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1import java.util.Arrays;
2
3public 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}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected