Problem 139
Gas Station
Medium · 20 pts · Array, Greedy
Problem
N gas stations stand on a circular route. Station i provides gas[i] units of fuel, and driving from station i to the next station (i + 1, or station 0 after the last one) uses cost[i] units. Your car starts with an empty tank at one station of your choice, refuels at every station, and must drive around the whole circle once. Find the starting station, or print -1 if no start works. If a solution exists, it is unique. If the total gas is less than the total cost, no start works. Otherwise, scan once: whenever the tank would go negative, the start must be after the current station, so reset the tank and move the candidate start forward.
Input
First line: integer N. Second line: N values gas[i]. Third line: N values cost[i].
Output
Print the zero-based starting index, or -1.
Constraints
1 <= N <= 100000; 0 <= gas[i], cost[i] <= 10000
Example input
5 1 2 3 4 5 3 4 5 1 2
Example output
3
Explanation
Starting at station 3: take 4 and use 1 (tank 3), take 5 and use 2 (tank 6), take 1 and use 3 (tank 4), take 2 and use 4 (tank 2), take 3 and use 5 (tank 0), arriving back at station 3. The tank never drops below 0, so the answer is 3.