Skip to content
BytePatterns

Circular Fuel Route

MediumGreedy#greedy#running-sum~25m

Problem

Fuel stations sit on a circular road. Station i lets you take on fuel[i] units, and driving from station i to the next one burns cost[i] units. You start at one station with an empty tank and drive all the way round, never letting the tank drop below zero. Return the index of the first station from which the full loop succeeds, or -1 if none does.

Examples

Input:  fuel = [1, 2, 3, 4, 5], cost = [3, 4, 5, 1, 2]
Output: 3
Why:    from station 3 the tank reads 3, 6, 4, 2, 0 after each leg
Input:  fuel = [2, 3, 4], cost = [3, 4, 3]
Output: -1
Why:    9 units of fuel cannot pay for 10 units of driving
Input:  fuel = [5], cost = [4]
Output: 0
Why:    edge case, a single station only has to pay for its own loop

Hints

0 / 3

Stuck on the idea rather than the code? Gas Station covers it.