-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGasStation.java
More file actions
30 lines (24 loc) · 761 Bytes
/
GasStation.java
File metadata and controls
30 lines (24 loc) · 761 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
public class GasStation {
public static int canCompleteCircuit(int[] gas, int[] cost) {
int totalTank = 0;
int currTank = 0;
int startIndex = 0;
for (int i = 0; i < gas.length; i++) {
int gain = gas[i] - cost[i];
totalTank += gain;
currTank += gain;
if (currTank < 0) {
startIndex = i + 1;
currTank = 0;
}
}
return totalTank >= 0 ? startIndex : -1;
}
public static void main(String[] args) {
// Example input
int[] gas = {1, 2, 3, 4, 5};
int[] cost = {3, 4, 5, 1, 2};
int result = canCompleteCircuit(gas, cost);
System.out.println("Output: " + result);
}
}