class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int before = 0;
int total = 0;
int loc = 0;
for (int i = 0; i < gas.length; i++) {
before += gas[i] - cost[i];
total += gas[i] - cost[i];
if (before < 0) {
loc = i + 1;
before = 0;
}
}
return total >= 0 ? loc : -1;
}
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Gas Station.
Memory Usage: 39 MB, less than 83.31% of Java online submissions for Gas Station.