sagelearnai

Minimum Number of Refueling Stops

Difficulty: Hard · Pattern: Greedy · LeetCode #871

A car starts at position 0 with startFuel liters, using 1 liter per mile. stations[i] = [position, fuel], sorted by position. Return the minimum number of refueling stops needed to reach target, or -1 if it's impossible. Each station's fuel can be fully taken at most once.

Examples

text
target = 1,   startFuel = 1,  stations = []                                   →  0
target = 100, startFuel = 1,  stations = [[10,100]]                           →  -1
target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]    →  2  (stop at 10 and 60)

Hints

  1. Imagine you could decide later whether you stopped at a station you already drove past.
  2. Keep every station you've passed in a max-heap. Whenever you can't reach the next point, take the largest fuel from the heap (one stop).

Approach

Deferred-decision greedy:

text
fuel = startFuel; stops = 0; heap = []
for each station (and finally the target as a pseudo-station):
    while fuel < position and heap: fuel += pop max; stops += 1
    if fuel < position: return -1
    push station fuel

Here fuel means the furthest reachable position. When we're stuck, the best stop to have made is the passed station with the most fuel. Using the largest available fuel first minimizes the number of stops (an exchange argument). O(n log n).

A DP alternative: dp[k] = farthest distance reachable with k stops, updated per station in reverse k order. That's O(n²).

Complexity

Time: O(n log n) with the heap (O(n²) with the DP). Space: O(n).

Python solution
import heapq

def minRefuelStops(target, startFuel, stations):
    heap, fuel, stops = [], startFuel, 0
    for pos, f in stations + [[target, 0]]:
        while fuel < pos and heap:
            fuel -= heapq.heappop(heap)
            stops += 1
        if fuel < pos:
            return -1
        heapq.heappush(heap, -f)
    return stops
JavaScript solution
function minRefuelStops(target, startFuel, stations) {
  // DP: dp[k] = farthest reachable distance using k stops.
  const n = stations.length, dp = new Array(n + 1).fill(0);
  dp[0] = startFuel;
  for (let i = 0; i < n; i++) {
    const [pos, f] = stations[i];
    for (let k = i; k >= 0; k--) if (dp[k] >= pos) dp[k + 1] = Math.max(dp[k + 1], dp[k] + f);
  }
  for (let k = 0; k <= n; k++) if (dp[k] >= target) return k;
  return -1;
}