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 targetstartFuel[position, fuel]
The limits are 1 <= target, startFuel <= 10^9
Example 1
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
Output: 0
Explanation: the starting fuel already covers the one mile.
Example 3
Output: -1
Explanation: the car runs dry at mile 1, before it gets to the station at mile 10.
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.
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 PriorityQueueCollections.reverseOrder()
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
- First, create the max-heap
, apassed withPriorityQueue . SetCollections.reverseOrder() toreach , the counterstartFuel to 0, andstops , the index of the next station the car has not passed yet, to 0.i is areach , because 500 stations of up to 10^9 liters each can add up to far more than the roughly 2.1 billion anlong holds.int - An outer
loop runs as long aswhile is less thanreach .target - Inside it, a second loop moves
forward over every station whose position is at mosti , and adds that station's fuel toreach .passed - If
is then empty, the car is stuck, so return -1.passed - Otherwise take the most fuel out of the heap with
, add it topassed.poll() , and add one toreach .stops - When the outer loop ends,
is at leastreach , so returntarget .stops
The main
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:
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 <=<
Complexity
The work is one walk of i
- Time: O(n log n) for n stations, because
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).i - 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