Skip to main content
Back to problems
#871
Hard Algorithms

Minimum number of refueling stops

Array Dynamic Programming Greedy Heap (Priority Queue)
41.1% acceptance
Feb 22, 2026
4863
93
A car travels from a starting position to a destination which is target miles east of the starting position. There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting position and has fueli liters of gas. The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car. Return the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1. Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
use std::collections::BinaryHeap;

impl Solution {
  pub fn min_refuel_stops(target: i32, start_fuel: i32, stations: Vec<Vec<i32>>) -> i32 {
    let mut heap = BinaryHeap::new();
    let mut fuel = start_fuel as i64;
    let mut stops = 0;
    let mut prev = 0i64;
    let target = target as i64;
    for s in &stations {
      let pos = s[0] as i64;
      let cap = s[1] as i64;
      fuel -= pos - prev;
      prev = pos;
      while fuel < 0 {
        if heap.is_empty() { return -1; }
        fuel += heap.pop().unwrap();
        stops += 1;
      }
      heap.push(cap);
    }
    fuel -= target - prev;
    while fuel < 0 {
      if heap.is_empty() { return -1; }
      fuel += heap.pop().unwrap();
      stops += 1;
    }
    stops
  }
}