871. Minimum Number of Refueling Stops
Problem
A car drives toward target miles away, starting with startFuel litres and burning 1 litre per mile. stations[i] = [position, fuel] lists gas stations in order of position; at a station you may take all of its fuel. Return the minimum number of refuelling stops to reach the target, or −1 if it's unreachable. Arriving anywhere with 0 fuel left still counts.
Example: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]] → 2
Constraints: up to 500 stations.
Drive as far as the fuel allows, pushing every station passed into a max-heap. When stuck, retroactively refuel at the biggest station passed (one stop). Fail if the heap is empty.
Complexity: O(n log n).
class Solution:
def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
h, reach, i, stops = [], startFuel, 0, 0
while reach < target:
while i < len(stations) and stations[i][0] <= reach:
heappush(h, -stations[i][1])
i += 1
if not h:
return -1
reach -= heappop(h)
stops += 1
return stops
assert Solution().minRefuelStops(1, 1, []) == 0
assert Solution().minRefuelStops(100, 1, [[10, 100]]) == -1
assert Solution().minRefuelStops(100, 10, [[10, 60], [20, 30], [30, 30], [60, 40]]) == 2
class Solution {
public int minRefuelStops(int target, int startFuel, int[][] stations) {
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
long reach = startFuel;
int i = 0, stops = 0;
while (reach < target) {
while (i < stations.length && stations[i][0] <= reach) pq.add(stations[i++][1]);
if (pq.isEmpty()) return -1;
reach += pq.poll();
stops++;
}
return stops;
}
}
type MaxHeap []int
func (h MaxHeap) Len() int { return len(h) }
func (h MaxHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h MaxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MaxHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h *MaxHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func minRefuelStops(target int, startFuel int, stations [][]int) int {
h, reach, i, stops := &MaxHeap{}, startFuel, 0, 0
for reach < target {
for i < len(stations) && stations[i][0] <= reach { // stations we could have stopped at
heap.Push(h, stations[i][1])
i++
}
if h.Len() == 0 {
return -1
}
reach += heap.Pop(h).(int) // retroactively stop at the biggest one
stops++
}
return stops
}