Search⌘ K
AI Features

Minimum Number of Refueling Stops

Understand how to calculate the minimum number of refueling stops required for a car to travel a specified distance. Learn to apply greedy algorithm strategies to optimize refueling decisions, handle edge cases, and work with station data effectively.

Statement

You need to find the minimum number of refueling stops that a car needs to make to cover a distance, target. For simplicity, assume that the car has to travel from west to east in a straight line. There are various fuel stations on the way that are represented as a 2-D array of stations, i.e., stations[i] =[di,fi]= [d_i, f_i], where did_i is the distance (in miles) of the ithi^{th} gas station from the starting position, and fif_i is the amount of fuel (in liters) that it stores. Initially, the car starts with k liters of fuel. The car consumes one liter of fuel for every mile traveled. Upon reaching a gas station, the car can stop and refuel using all the petrol stored at the station. If it cannot reach the target, the program returns 1−1.

Note: If the car reaches a station with 00 fuel left, it can refuel from that station, and all the fuel from that station can be transferred to the car. If the car reaches the target with 00 fuel left, it is still considered to have arrived.

Constraints:

  • 11 \leq target, k 109\leq 10^9
  • 00 \leq stations.length 900\leq 900
  • 1di<di+1<1 \leq d_{i} < d_{i+1}< target
  • 1fi<1091 \leq f_{i} < 10^9

Examples

Understand the problem

Let’s take a moment to make sure you've correctly understood the problem. The quiz below helps you check if you're solving the correct problem:

Minimum Number of Refueling Stops

1.

Suppose the starting fuel is 9, and the target to be achieved is 33. Which of the following is the correct option for the minimum number of refueling stops?

                           |   Distance |   Fuel    |
                           --------------------------
                           |      5     |     8     |
                           |      7     |    11     |
                           |     10     |     3     |
                           |     13     |     7     |
                           |     21     |     6     |
                                
A.

4

B.

3

C.

5

D.

2


1 / 2

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5

Try it yourself

Implement your solution in the following coding playground:

Java
usercode > MinimumRefuelStops.java
import java.util.*;
class MinimumRefuelStops {
public static int minRefuelStops(int target, int startFuel, int[][] stations) {
// Replace this placeholder return statement with your code
return -1;
}
}
Minimum Number of Refueling Stops