Minimum Number of Refueling Stops

hard heap greedy dynamic programming

Problem

A car starts with startFuel units of fuel and must reach a target miles away; one mile costs one unit. Along the way there are gas stations, where stations[i] = [position, fuel]. Return the minimum number of refueling stops to reach the target, or -1 if impossible.

Inputtarget = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output2
Refuel at the 60-unit station, then the 40-unit one.

import heapq

def min_refuel_stops(target, start_fuel, stations):
    heap, fuel, i, stops = [], start_fuel, 0, 0
    while fuel < target:
        while i < len(stations) and stations[i][0] <= fuel:
            heapq.heappush(heap, -stations[i][1])
            i += 1
        if not heap:
            return -1
        fuel += -heapq.heappop(heap)
        stops += 1
    return stops
function minRefuelStops(target, startFuel, stations) {
  const heap = new MaxHeap();   // largest fuel on top
  let fuel = startFuel, i = 0, stops = 0;
  while (fuel < target) {
    while (i < stations.length && stations[i][0] <= fuel)
      heap.push(stations[i++][1]);
    if (heap.isEmpty()) return -1;
    fuel += heap.pop();
    stops++;
  }
  return stops;
}
int minRefuelStops(int target, int startFuel, int[][] stations) {
    PriorityQueue<Integer> heap = new PriorityQueue<>(Collections.reverseOrder());
    long fuel = startFuel;
    int i = 0, stops = 0;
    while (fuel < target) {
        while (i < stations.length && stations[i][0] <= fuel)
            heap.add(stations[i++][1]);
        if (heap.isEmpty()) return -1;
        fuel += heap.poll();
        stops++;
    }
    return stops;
}
int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) {
    priority_queue<int> heap;
    long long fuel = startFuel;
    int i = 0, stops = 0;
    while (fuel < target) {
        while (i < (int)stations.size() && stations[i][0] <= fuel)
            heap.push(stations[i++][1]);
        if (heap.empty()) return -1;
        fuel += heap.top(); heap.pop();
        stops++;
    }
    return stops;
}
Time: O(n log n) Space: O(n)