#134 · Greedy · Advanced · 125 XP · about 22 min
Fuel stations stand around a circular road. At station i you can take on fuel[i] liters, and driving from station i to the next one burns cost[i] liters; after the last station the road leads back to station 0. The car starts with an empty tank, and the tank can hold any amount.
Write start_station(fuel, cost) that returns the index of a station where you can start, drive one full lap and arrive back without ever running out, or -1 if no station works. If several stations work, return the smallest index. Arriving at a station with an empty tank is fine.
start_station([4, 1, 5, 2], [3, 3, 2, 4]) # returns 2 start_station([2, 2], [3, 2]) # returns -1 start_station([3, 3, 3], [3, 3, 3]) # returns 0
Starting at station 2 in the first example, the tank holds 3, then 1, then 2, then 0 liters after each leg, so the lap is completed.
1 <= len(fuel) == len(cost) <= 100000 <= fuel[i], cost[i] <= 10000Ready?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.