The Minimum Number of Refueling Stops problem involves finding the minimum number of refueling stops required to reach a target distance with a given starting fuel. You are provided with a list of gas stations, each with a location and fuel capacity.
class Solution {
public int minRefuelStops(int target, int startFuel, int[][] stations) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
int fuel = startFuel, stops = 0, index = 0;
while (fuel < target) {
// Add all reachable stations to the max-heap
while (index < stations.length && stations[index][0] <= fuel) {
maxHeap.offer(stations[index][1]);
index++;
}
// If no station is reachable and target is not reached, return -1
if (maxHeap.isEmpty()) return -1;
// Refuel with the station providing the most fuel
fuel += maxHeap.poll();
stops++;
}
return stops;
}
}
O(N log N)
, where N
is the number of stations.O(N log N)
.Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
- Stop at station 0 (10, 60) to refuel. Fuel = 10 + 60 = 70.
- Stop at station 3 (60, 40) to refuel. Fuel = 70 + 40 = 110.
- Reach the target with 2 stops.
-1
.