Gas Station LeetCode solution in C++

1
class Solution {
2
public:
3
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
4
int n = gas.size();
5
int start = -1;
6

7
int sum = 0, gastillnow = 0;
8
for (int i = 0; i < 2 * n; i++) {
9
if (start == i % n) {
10
return i % n;
11
}
12
if (gas[i % n] + gastillnow >= cost[i % n]) { // we can start from this index
13
if (start == -1) start = i;
14
gastillnow += gas[i % n] - cost[i % n];
15
} else if (gastillnow + gas[i % n] < cost[i % n]) { // previous start index was wrong we have
16
// to start from another
17
start = -1;
18
gastillnow = 0;
19
}
20
}
21
return -1;
22
}
23
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0