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
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
There are 6 units of gas in all and the legs need 9, so no start can work.
Example 3
Constraints
1 ≤ n ≤ 10⁵gas.length = cost.length = n0 ≤ gas[i], cost[i] ≤ 10⁴- At most one station can start a trip all the way round
Practice this in an AI round
30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.
Your first AI round is free.
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