Minimum Number of Refueling Stops — LeetCode 871 Python Solution
HardGreedyArrayDynamic ProgrammingHeap (Priority Queue)
- Problem
- #871
- Pattern
- Heap / Priority Queue
- Reading time
- 3 min
- Source
- leetcode.com
The problem
A car travels from a starting position to a destination which is target miles east of the starting position. There are gas stations along the way.
Example
- Input
- target = 1, startFuel = 1, stations = []
- Output
- 0
- Explanation
- We can reach the target without refueling.
Python solution
Python
class Solution:
def minRefuelStops(
self, target: int, startFuel: int, stations: List[List[int]]
) -> int:
pq = []
ans = pre = 0
stations.append([target, 0])
for pos, fuel in stations:
dist = pos - pre
startFuel -= dist
while startFuel < 0 and pq:
startFuel -= heappop(pq)
ans += 1
if startFuel < 0:
return -1
heappush(pq, -fuel)
pre = pos
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 871. Minimum Number of Refueling Stops is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 871. Minimum Number of Refueling Stops?
- LeetCode 871. Minimum Number of Refueling Stops is rated Hard on LeetCode.
- What is the time complexity of LeetCode 871. Minimum Number of Refueling Stops?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 871. Minimum Number of Refueling Stops?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 871. Minimum Number of Refueling Stops cover?
- LeetCode 871. Minimum Number of Refueling Stops is tagged Greedy, Array, Dynamic Programming and Heap (Priority Queue) on LeetCode.