871 Minimum Number of Refueling Stops
1. Questions
A car travels from a starting position to a destination which istarget
miles east of the starting position.
Along the way, there are gas stations. Eachstation[i]
represents a gas station that isstation[i][0]
miles east of the starting position, and hasstation[i][1]
liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel
liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.
When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return-1
.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation:
We can't reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
Note:
1 <= target, startFuel, stations[i][1] <= 10^9
0 <= stations.length <= 500
0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
2. Implementation
(1) Heap
思路: 贪心的思想,用一个最大堆记录当前fuel能到达的stations, 并将有最大油量的station的油,加给当前的fuel,stop加一,直到curFuel >= target。如果curFuel < target的情况下,maxHeap为空,说明无法到达target, 返回-1.
class Solution {
public int minRefuelStops(int target, int startFuel, int[][] stations) {
if (startFuel >= target) {
return 0;
}
if (stations == null || stations.length == 0) {
return -1;
}
int curFuel = startFuel;
PriorityQueue<Integer> maxHeap = new PriorityQueue(Collections.reverseOrder());
int stops = 0;
int i = 0;
while (curFuel < target) {
while (i < stations.length && stations[i][0] <= curFuel) {
maxHeap.add(stations[i][1]);
++i;
}
if (maxHeap.isEmpty()) {
return -1;
}
curFuel += maxHeap.remove();
++stops;
}
return stops;
}
}
(2) 0-1背包
3. Time & Space Complexity
Heap: 时间复杂度O(nlogn), 空间复杂度O(n)
Last updated
Was this helpful?