Intuition
For each station, simulate the full trip around the circuit. If the tank never goes negative, that station is the answer.
Explanation
Brute Force
Try starting at each station 0 through n-1. For each candidate start, simulate driving around the circuit: at each stop, add gas[i] and subtract cost[i]. If the tank goes negative at any point, this start does not work — move to the next candidate.
Two nested loops give O(n^2) time. Space is O(1) since we only track the current tank level.
Why it is slow: Each candidate start re-simulates the entire circuit from scratch, repeating work that a cleverer approach can avoid.
Implementation
import java.util.*;
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int n = gas.length;
for (int start = 0; start < n; start++) {
int tank = 0;
boolean success = true;
for (int j = 0; j < n; j++) {
int station = (start + j) % n;
tank += gas[station] - cost[station];
if (tank < 0) {
success = false;
break;
}
}
if (success) return start;
}
return -1;
}
}