Practice · Greedy · 1 of 4

Drive Once Around a Ring Road

Fuel stations stand around a circular road, numbered 0 to n − 1. At station i you can take gas[i] units of fuel, and driving from station i to the next one (station i + 1, or station 0 after the last) uses cost[i] units.

Your car's tank holds any amount and starts empty. Return the index of the station where you can start, fill up, and drive once around the whole road, filling up at every station on the way, without the tank ever going below zero. Return -1 if no starting station works.

The tests are chosen so that when a starting station exists, it is the only one.

Example 1

Input
gas = [1, 6, 2, 3], cost = [3, 1, 3, 4]
Output
1
Starting at station 1, the tank holds 5, 4, 3 and finally 1 unit after each stretch of road.

Example 2

Input
gas = [3, 2], cost = [2, 4]
Output
-1
The stations hold 5 units in all, but the whole road costs 6.

Constraints

  • gas and cost have the same length n, from 1 to 10⁴.
  • 0 ≤ gas[i], cost[i] ≤ 10⁴
  • When a starting station exists, exactly one does.