https://leetcode.com/problems/gas-station/?envType=study-plan-v2&envId=top-interview-150
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int n = gas.size();
vector<int> diff(n);
for (int i = 0; i < n; i++) diff[i] = gas[i] - cost[i];
int r = 0;
while (r < n) {
int idx = r;
int cur = 0;
while (1) {
cur += diff[idx % n];
if (cur < 0) {
r = idx + 1;
break;
}
idx += 1;
if ((idx % n) == r) return r;
}
}
return -1;
}
};
Time Complexity: O(n)
Space: O(n)