Minimum Number of Refueling Stops

Minimum stops to reach the target — when you "run out", retroactively take the largest skipped tank from a max-heap.

Hard
Time O(n log n) Space O(n)
LeetCode
5 min read
greedy heaps

Problem#

Start with startFuel units. stations[i] = [position, fuel]. Return minimum refueling stops to reach target, or -1 if impossible.

Examples#

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

Constraints#

  • 0 <= n <= 500.

Hints#

Hint 1
Defer refueling: pass every station, push its fuel into a max-heap. When you run out of fuel mid-segment, retroactively use the largest tank you passed.

Approach#

Iterate stations. Push each reachable station’s fuel into a max-heap. While fuel can’t reach the next station, pop the heap top (largest deferred refill); count a stop. If heap empty and still short → -1.

Solution#

Minimum Refueling Stops
class Solution {
public:
int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) {
priority_queue<int> pq;
int stops = 0, fuel = startFuel, i = 0;
const int n = stations.size();
while (fuel < target) {
while (i < n && stations[i][0] <= fuel) pq.push(stations[i++][1]);
if (pq.empty()) return -1;
fuel += pq.top(); pq.pop();
++stops;
}
return stops;
}
};

Editorial#

The greedy choice is “when forced to stop, take the largest tank you’ve passed”. Saving large tanks for later (rather than committing to refuel at the first one) is what minimizes stop count. The max-heap of passed-station fuels gives O(log n) per operation.

Complexity#

  • Time: O(n log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.