09. Minimum Number of Refueling Stops

Difficulty:HardPattern:Greedy Max-Heap Priority SearchTime:O(n log n)Space:O(n)

A car travels to target starting with startFuel liters. Along the way are gas stations where stations[i] = [position, fuel]. Return the minimum number of refueling stops to reach target.

How It Works & Algorithmic Design

Solves using Greedy Max-Heap Fuel Selection:

  1. Max-Heap: Store gas amounts of passed stations.
  2. Traversal: Loop through stations plus target position:
    • While current maxReach < station.position:
      • If heap is empty: cannot reach next station $\to$ return -1.
      • Pop largest available gas amount from heap: maxReach += maxHeap.pop(), stops++.
    • Push current station's fuel onto heap.
  3. Return: stops when target reached.

Why This Approach Works Best

Greedily refueling at the largest passed gas stations maximizes distance gained per stop in $O(n \log n)$ time.

Example Walkthrough

Input

target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]

Target and gas stations.

Greedy Stops

Refuel 60 at pos 10 (reach 70) -> Refuel 40 at pos 60 (reach 110).

2 total stops.

Output

2

Minimum fuel stops.

Answer: Minimum Number of Refueling Stops implementation

function minRefuelStops(target, startFuel, stations) {
  const heap = []; // Max-Heap simulated
  let maxReach = startFuel, stops = 0, idx = 0;
  while (maxReach < target) {
    while (idx < stations.length && stations[idx][0] <= maxReach) {
      heap.push(stations[idx][1]);
      heap.sort((a, b) => b - a);
      idx++;
    }
    if (heap.length === 0) return -1;
    maxReach += heap.shift();
    stops++;
  }
  return stops;
}

Greedily consume maximum available fuel from passed stations using a Max-Heap.

Key Takeaways
  • Store passed gas stations in Max-Heap instead of stopping immediately.

  • Pop largest fuel amount when current range cannot reach next milestone.

  • Executes in $O(n \log n)$ time.