Gas Station

Medium Greedy AI round

There are n gas stations in a circle. Station i has gas[i] units of gas you can take, and driving from station i to the next one costs cost[i] units. The next station after the last one, station n - 1, is station 0.

You choose one station to start at, with an empty tank. At each station you take all of its gas, then drive on to the next station, which needs the tank to hold at least that leg's cost: the tank may never go below zero. The trip ends when you are back at the station you started from, having driven every leg once.

Return the number of the station you can start at to make that trip, or -1 if there is none.

If a trip is possible, there is only one station that can start it.

Example 1

Input: gas = [3,1,5,2], cost = [2,4,3,1]
Output: 2

From station 2: take 5, drive 3 (2 left); take 2 at station 3, drive 1 (3 left); take 3, drive 2 (4 left); take 1, drive 4 (1 left) and you are back. Any other station runs dry on the way.

Example 2

Input: gas = [2,3,1], cost = [3,3,3]
Output: -1

There are 6 units of gas in all and the legs need 9, so no start can work.

Example 3

Input: gas = [5,0,0,3,0], cost = [1,3,3,0,1]
Output: 3

Constraints

  • 1 ≤ n ≤ 10⁵
  • gas.length = cost.length = n
  • 0 ≤ gas[i], cost[i] ≤ 10⁴
  • At most one station can start a trip all the way round

Watch the explanation

More Greedy

  • Largest NumberAI round · Medium
  • CandyAI round · Hard
  • Increasing Triplet SubsequenceMedium
  • Minimum Number of Arrows to Burst BalloonsMedium
  • Can Place FlowersEasy
All Greedy problems