public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int posSum = 0, circuitSum = 0;
int index = -1;
for(int i = 0; i < gas.length; i++) {
posSum += (gas[i] - cost[i]);
circuitSum += (gas[i] - cost[i]);
if(posSum < 0) {
posSum = 0;
index = i;
}
}
return circuitSum >= 0 ? index + 1 : -1;
}
}
Time: O(n)
Space: O(1)