Minimum Number of Refueling Stops

Hard · Heap & Counting · Array · Dynamic Programming · Greedy · Heap (Priority Queue)

Problem

A car drives east from position 0 toward a destination target miles away. It starts with startFuel litres, burns one litre per mile, and has an unlimited tank.

Along the way are gas stations stations[i] = [position_i, fuel_i], sorted by position. When the car stops at a station it takes all of that station's fuel. Reaching a station or the destination with exactly 0 fuel left is fine.

Return the minimum number of refuelling stops needed to reach target, or -1 if it is impossible.

Examples

Input: target = 50, startFuel = 20, stations = [[10,10],[20,30],[40,5]]
Output: 1

Drive to mile 20 with an empty tank, take 30 litres there, and reach mile 50.

Input: target = 10, startFuel = 3, stations = [[5,10]]
Output: -1

The car runs dry at mile 3, before the only station.

Input: target = 8, startFuel = 8, stations = []
Output: 0

The starting fuel is exactly enough.

Constraints

Approaches

Follow-up

The DP baseline also answers more than the question asked: far[t] for every number of stops. The use cases flip the question (with at most k stops, how far can the car get?) and apply the same "undo the worst choice so far" heap to keeping prefix sums non-negative.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…