Gas Station LeetCode solution in Java

1
class Solution {
2
public int canCompleteCircuit(int[] gas, int[] cost) {
3
// *Upvote will be appreciated*
4
int totalFuel = 0;
5
int totalCost = 0;
6
int n = gas.length;
7
for (int i = 0; i < n; i++) {
8
totalFuel += gas[i];
9
}
10
for (int i = 0; i < n; i++) {
11
totalCost += cost[i];
12
}
13
// if totalfuel < totalCost then It is not possible to tavel
14
if (totalFuel < totalCost) {
15
return -1;
16
}
17

18
// It is greather then There may be an Answer
19
int start = 0;
20
int currFuel = 0;
21
for (int i = 0; i < n; i++) {
22
currFuel += (gas[i] - cost[i]);
23
if (currFuel < 0) { // It Current Fuel is less than 0 mean we can't star from that index
24
start = i + 1; // so we start from next index
25
currFuel = 0;
26
}
27
}
28
return start;
29
}
30
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0