-
-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy pathGasStation.java
More file actions
35 lines (27 loc) · 815 Bytes
/
Copy pathGasStation.java
File metadata and controls
35 lines (27 loc) · 815 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
package leetcode.medium;
public class GasStation {
int canCompleteCircuit(int[] gas, int[] cost) {
int totalGas = 0, totalCost = 0;
// Calculate total gas and total cost
for (int i = 0; i < gas.length; i++) {
totalGas += gas[i];
totalCost += cost[i];
}
// If total gas is less than total cost, return -1
if (totalGas < totalCost) {
return -1;
}
int currentGas = 0, startIndex = 0;
// Iterate through the gas stations
for (int i = 0; i < gas.length; i++) {
currentGas += gas[i] - cost[i];
// If current gas is negative, reset start index and current gas
if (currentGas < 0) {
startIndex = i + 1;
currentGas = 0;
}
}
// Return the starting index if a valid circuit exists
return startIndex;
}
}