Minimum Number of Refueling Stops

Reach a destination with the fewest fuel stops by driving past stations and choosing the best ones afterwards.

A car starts at mile 0 and drives to a destination target miles east. It begins with startFuel liters of fuel, uses one liter per mile, and its tank can hold any amount. Gas stations along the way are given as [position, fuel] pairs, sorted by position. Stopping at a station adds all of its fuel to the tank. Return the fewest stops needed to reach the target, or -1 if it cannot be reached. A car that arrives at a station or at the target with 0 fuel left still counts as having arrived.

The limits are 1 <= target, startFuel <= 10^9, at most 500 stations, and each station holds between 1 and 10^9 liters.

Example 1
Input: target = 100, startFuel = 10, stations = [[10, 60], [20, 30], [30, 30], [60, 40]]
Output: 2
Explanation: stop at mile 10 for 60 liters, then at mile 60 for 40 liters. In total the car has 10 + 60 + 40 = 110 liters, enough for 100 miles.
Example 2
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: the starting fuel already covers the one mile.
Example 3
Input: target = 100, startFuel = 1, stations = [[10, 100]]
Output: -1
Explanation: the car runs dry at mile 1, before it gets to the station at mile 10.
Solution

The Idea

On a long drive you look at the gas stations along the road and try to stop as few times as possible. In Example 1 the destination is 100 miles away and the car starts with 10 liters, enough for 10 miles. There are stations at miles 10, 20, 30 and 60, holding 60, 30, 30 and 40 liters.

The first stop is forced. The car arrives at mile 10 with an empty tank, so it must take the 60 liters there, which is enough to get to mile 70. But then it drives past mile 20 with 50 liters left. Should it stop for the 30 liters there? At that moment the car cannot tell whether it will need them.

The way out is to put the decision off. What decides how far the car gets is the total fuel it has taken, not where it took it. So the car can drive past a station, remember it, and later, when the fuel runs out, act as if it had stopped there after all. Call the farthest mile the car can get to with the fuel taken so far its reach.

Look at the picture below. It shows the road of Example 1 with the fuel at each station, and one bar for each value of the reach.

A road from mile 0 to the target at mile 100, with stations at miles 10, 20, 30 and 60 holding 60, 30, 30 and 40 liters. The reach starts at 10. Stopping at mile 10 gives reach 70. Of the passed stations 30, 30 and 40, the largest, 40 at mile 60, gives reach 110, past the target.

In the row labelled "start: reach 10", the car has passed one station, the one with 60 liters, and it takes it. In the row labelled "stop at mile 10 (+60): reach 70", the car has now also passed the stations at miles 20, 30 and 60. A reach of 70 is short of the target, so one more stop is needed.

Which of the passed stations should that stop be? Every stop costs the same, one, so the car takes the one with the most fuel, 40 liters at mile 60. The last row, "stop at mile 60 (+40): reach 110", crosses the dashed target line after two stops. The two stations with 30 liters, drawn as "passed, never used", were never needed.

Picking each stop by what helps most right now, here the largest fuel among the stations behind the car, is called a greedy choice. Making only greedy choices does not always give the best answer, so this problem needs a reason why it does.

Solution Approach

The plan needs four pieces: a reason not to try every set of stations, a reason why the largest passed station is a safe stop, a fast way to find that station, and a rule for giving up.

Trying every set of stations

Why not test every choice of stops? Each station is either a stop or not, so n stations give 2n sets to check. Example 1 has only 16, but 30 stations already give 1,073,741,824 sets, far too many to try one by one.

Choosing the largest passed station

Why is the largest passed station always a safe stop? When the reach falls short, the car needs one more stop, and it can only be at a station within the reach. Each of those costs one stop, and the largest pushes the reach farthest. Any station a smaller pick would bring within reach, the largest brings within reach too, and the other passed stations stay available for later stops.

The stops chosen this way are not always in road order. The car may take the fuel of mile 60 at one stop and the fuel of mile 20 at a later one. That is allowed, because the car did get to mile 20, and only the total fuel decides the reach.

Keeping the passed stations in a heap

How do we find the largest passed station quickly? Searching the whole list at every stop is slow when many stations pile up. A heap keeps values so that the largest can be taken out, and a new one put in, in about log n steps for n values. Here it holds the fuel amounts of the passed stations: after the second row of the picture it holds 30, 30 and 40, and hands out 40 first.

In Java the heap is a PriorityQueue of fuel amounts. Left as it is, it would hand out 30 before 40, the smallest amount first, which is called a min-heap. Giving it Collections.reverseOrder() as its comparator turns that around, so it becomes a max-heap that hands out the 40 first:

Java
PriorityQueue<Integer> passed = new PriorityQueue<>(Collections.reverseOrder());

When the target cannot be reached

When should the car give up? If the reach is still short of the target and the heap is empty, every passed station has been used and no stop can help, so the answer is -1. In Example 3 the reach is 1 and the one station is at mile 10, so the heap never gets anything.

Java Solution

The method minRefuelStops works in these steps:

  1. First, create the max-heap passed, a PriorityQueue with Collections.reverseOrder(). Set reach to startFuel, the counter stops to 0, and i, the index of the next station the car has not passed yet, to 0. reach is a long, because 500 stations of up to 10^9 liters each can add up to far more than the roughly 2.1 billion an int holds.
  2. An outer while loop runs as long as reach is less than target.
  3. Inside it, a second loop moves i forward over every station whose position is at most reach, and adds that station's fuel to passed.
  4. If passed is then empty, the car is stuck, so return -1.
  5. Otherwise take the most fuel out of the heap with passed.poll(), add it to reach, and add one to stops.
  6. When the outer loop ends, reach is at least target, so return stops.

The main method runs the three examples, a station exactly at the starting reach, three small stations that are all needed, and a start with more fuel than the trip takes.

Java
import java.util.Collections;
import java.util.PriorityQueue;

public class MinimumNumberOfRefuelingStops {

    public static int minRefuelStops(int target, int startFuel, int[][] stations) {
        // fuel of the stations we have driven past, largest first
        PriorityQueue<Integer> passed = new PriorityQueue<>(Collections.reverseOrder());
        long reach = startFuel;    // the farthest mile we can get to with the stops so far
        int stops = 0;
        int i = 0;                 // the next station not yet passed
        while (reach < target) {
            while (i < stations.length && stations[i][0] <= reach) {
                passed.add(stations[i][1]);   // a station we could have stopped at
                i++;
            }
            if (passed.isEmpty()) {
                return -1;                    // stuck before the target
            }
            reach += passed.poll();           // stop at the best station behind us
            stops++;
        }
        return stops;
    }

    public static void main(String[] args) {
        System.out.println(minRefuelStops(100, 10,
                new int[][] {{10, 60}, {20, 30}, {30, 30}, {60, 40}}));
        System.out.println(minRefuelStops(1, 1, new int[][] {}));
        System.out.println(minRefuelStops(100, 1, new int[][] {{10, 100}}));
        System.out.println(minRefuelStops(100, 10, new int[][] {{10, 90}}));
        System.out.println(minRefuelStops(100, 25,
                new int[][] {{25, 25}, {50, 25}, {75, 25}}));
        System.out.println(minRefuelStops(50, 80, new int[][] {{10, 100}}));
    }
}

Running it prints:

Output
2
0
-1
1
3
0

The answers 2, 0 and -1 on the first three lines match Examples 1, 2 and 3. The fourth line, 1, comes from the station at mile 10 with 90 liters. The car gets there on an empty tank, and those 90 liters take the reach from 10 to 100, exactly the target.

The fifth line, 3, needs every station: each adds 25 liters, so the reach goes from 25 to 50, 75 and finally 100. The last line is 0, because 80 liters already cover the 50 miles and the outer loop never runs.

The <= in the second loop matters. With a strict <, a station exactly at the reach is never counted as passed. The car in Example 1 then never takes the 60 liters at mile 10, and that version returns -1 for both Example 1 and the fourth input.

Complexity

The work is one walk of i over the stations, plus heap steps for the stations it passes.

  • Time: O(n log n) for n stations, because i only moves forward, so each station goes into the heap once and comes out at most once, and each of those heap steps costs O(log n).
  • Space: O(n), because the heap can end up holding the fuel of every station, when the starting fuel carries the car past all of them before its first stop.

Passing things now and choosing among them later with a heap is also how Furthest Building You Can Reach decides where to use its ladders.