#871

Minimum Number of Refueling Stops

Hard
ArrayDynamic ProgrammingGreedyHeap (Priority Queue)GreedyPriority QueueDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution uses a greedy approach with a priority queue to always refuel at the station with the most fuel available when needed. This ensures that we minimize the number of stops while maximizing the fuel we can carry forward.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a max-heap (priority queue) to store fuel from reachable stations.
  2. 2Step 2: Iterate through each station, checking if it can be reached with current fuel.
  3. 3Step 3: If reachable, add its fuel to the heap and check if the destination can be reached with current fuel.
  4. 4Step 4: If not, refuel from the station with the most fuel from the heap until we can reach the destination or exhaust options.
solution.py15 lines
1import heapq
2
3def minRefuelStops(target, startFuel, stations):
4    max_heap = []
5    stops = 0
6    current_fuel = startFuel
7    stations.append((target, 0))
8    for position, fuel in stations:
9        while current_fuel < position:
10            if not max_heap:
11                return -1
12            current_fuel += -heapq.heappop(max_heap)
13            stops += 1
14        heapq.heappush(max_heap, -fuel)
15    return stops

Complexity note: The time complexity is O(n log n) due to the priority queue operations for each station, where n is the number of stations.

  • 1Greedy algorithms can often yield optimal solutions for problems involving choices over time.
  • 2Using a priority queue allows us to efficiently manage the best options available at each step.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.