Minimum Number of Refueling Stops - Problem
Imagine you're planning a cross-country road trip with limited fuel! 🚗
Your car needs to travel from the starting position to a destination that is target miles away. Along the route, there are several gas stations positioned at different distances, each containing a specific amount of fuel.
The Challenge: Find the minimum number of refueling stops needed to reach your destination, or return -1 if it's impossible.
Key Details:
- Your car starts with
startFuelliters of fuel - The car consumes 1 liter per mile
- Gas stations are represented as
[position, fuel]pairs - When you stop at a station, you take all the fuel available there
- You can reach a station or destination with exactly 0 fuel remaining
Goal: Return the minimum number of stops needed, or -1 if the journey is impossible.
Input & Output
example_1.py — Basic Journey
$
Input:
target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
›
Output:
2
💡 Note:
Start with 10 fuel, reach station at position 10. Refuel to get 60 more fuel (total distance reachable: 70). Travel to position 70, but need to reach 100. Look back at passed stations: used [10,60], have [20,30], [30,30], [60,40] available. Take the best one [60,40] retroactively. Now we can reach 70 + 40 = 110 ≥ 100. Total stops: 2.
example_2.py — Impossible Journey
$
Input:
target = 100, startFuel = 50, stations = [[25,25],[50,50]]
›
Output:
1
💡 Note:
Start with 50 fuel, can reach position 50. Need 50 more fuel to reach target 100. Can use station [25,25] retroactively - with 25 additional fuel, can reach 50+25=75. Can also use station [50,50] retroactively - with 50 additional fuel, can reach 50+50=100. Choose [50,50] for 1 total stop.
example_3.py — No Refueling Needed
$
Input:
target = 100, startFuel = 100, stations = [[10,60],[20,30],[30,30],[60,40]]
›
Output:
0
💡 Note:
We start with enough fuel (100) to reach the target (100) directly without any refueling stops.
Constraints
- 1 ≤ target, startFuel ≤ 109
- 0 ≤ stations.length ≤ 500
- 0 < stations[i][0] < target
- 1 ≤ stations[i][1] < 109
- All stations are positioned before the target
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code