Problem. gas stations on a circle; station gives fuel and reaching the next one costs . Find a start from which you can complete the circuit with an initially empty tank, or report none.
Answer: a start exists iff ; one pass finds it: whenever the running tank goes negative, the next station becomes the candidate start.
int gasStart(const vector<long long>& gas, const vector<long long>& cost) { // start index completing the circuit, or -1
long long total = 0, tank = 0; int start = 0;
for (int i = 0; i < sz(gas); i++) {
total += gas[i] - cost[i]; tank += gas[i] - cost[i];
if (tank < 0) start = i + 1, tank = 0;
}
return total >= 0 ? start : -1;
}Proof: the one-pass greedy
If the tank first becomes negative after station when starting at , then no station in works as a start: starting at any in between, you arrive at with a non-negative tank from , so starting at with an empty tank can only be worse, and it also fails by station . So the candidate jumps to . Let be the final candidate: the suffix from to never goes negative, and the prefix has total . If the total is , the suffix surplus covers every prefix deficit (each prefix sum is at least , otherwise the total would be negative), so the circuit from succeeds. If the total is negative, no start works because the whole circuit consumes more than it gives. Checked against trying every start.