09. Minimum Number of Refueling Stops
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:
- Max-Heap: Store gas amounts of passed stations.
- 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++.
- If heap is empty: cannot reach next station $\to$ return
- Push current station's fuel onto heap.
- While current
- Return:
stopswhen 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
target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Target and gas stations.
Refuel 60 at pos 10 (reach 70) -> Refuel 40 at pos 60 (reach 110).
2 total stops.
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.
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.