1038. Where to Start the Circuit
n fuel stations stand in a circle. Station i gives you gas[i] units, and
driving from station i to the next one costs cost[i] units. You start with an
empty tank and may begin anywhere.
Print the 0-based index of a station you can start from and complete the full
circle without the tank ever going negative, or -1 if no such station exists.
When more than one works, print the smallest such index.
Trying every start costs O(n^2). Two observations reduce it to one pass.
First, a circuit is possible at all only when the total gas is at least the total
cost. That single sum decides between an answer and -1, before any start is
considered.
Second, suppose you begin at s and the tank first goes negative on arriving at
station j. Then no station between s and j can be the answer either. Each
such station was reached with a tank that was zero or more, so starting there
gives you no more fuel than you already had, and you would run dry no later. So
the next candidate is j + 1, and the scan never goes back.
Together: one pass tracking the running tank, resetting the candidate start whenever it falls below zero, plus the total to decide whether an answer exists.
Constraints - `1 ≤ n ≤ 200000` - `0 ≤ gas[i] ≤ 100000` - `0 ≤ cost[i] ≤ 100000`
Input
The first line contains an integer n.
The second line contains n space-separated values: gas[0] to gas[n-1].
The third line contains n space-separated values: cost[0] to cost[n-1].
Output
Print the smallest 0-based starting index that allows a full circuit, or -1 if there is none.
Hints
Four rungs, in order. The last two open once you have submitted an attempt. A wrong one counts.