public int canCompleteCircuit(int[] gas, int[] cost) { int sumGas = 0; int sumCost = 0; for (int i = 0; i < gas.length; i++) { sumGas += gas[i]; sumCost += cost[i]; } if (sumGas < sumCost) { return -1; } int total = 0; // tank since the current start int res = 0; for (int i = 0; i < gas.length; i++) { total += gas[i] - cost[i]; if (total < 0) { total = 0; res = i + 1; // restart after i } } return res;}
- i
- —
- gas[i] − cost[i]
- —
- total
- —
- res
- —
Why it works
- Brute force simulates the loop from every start: n starts, n stations each, O(n²).
- Enough fuel overall means some start works. If
sumGas ≥ sumCost, the start right after the lowest point of the running tank never dips below zero. If the sum is short, no start can work: return-1at once. - A failed run rules out its whole stretch. If the tank from
resgoes negative ati, then starting at any station betweenresandialso fails: you would arrive there with a tank ≥ 0 when starting fromres, and even that was not enough. So jump straight toi + 1. One pass: O(n) time, O(1) space. - Pitfall: you do not need to wrap around and re-check the stations before
res. The total check already guarantees the surplus from the last run covers the deficit of the earlier ones. - Related: the same "drop a negative prefix" reset is Kadane's algorithm in Maximum Subarray (53).