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:
Example 2:
Example 3:
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.
(2) 0-1背包
3. Time & Space Complexity
Heap: 时间复杂度O(nlogn), 空间复杂度O(n)
Last updated
Was this helpful?