Furthest Building You Can Reach — LeetCode 1642 Python Solution
- Problem
- #1642
- Pattern
- Heap / Priority Queue
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given an integer array heights representing the heights of buildings, some bricks, and some ladders. You start your journey from building 0 and move to the next building by possibly using bricks or ladders.
Example
- Input
- heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
- Output
- 4
- Explanation
- Starting at building 0, you can follow these steps:
Python solution
class Solution:
def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:
h = []
for i, a in enumerate(heights[:-1]):
b = heights[i + 1]
d = b - a
if d > 0:
heappush(h, d)
if len(h) > ladders:
bricks -= heappop(h)
if bricks < 0:
return i
return len(heights) - 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(1) to O(n) auxiliary |
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 1642. Furthest Building You Can Reach 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 1642. Furthest Building You Can Reach?
- LeetCode 1642. Furthest Building You Can Reach is rated Medium on LeetCode.
- What topics does LeetCode 1642. Furthest Building You Can Reach cover?
- LeetCode 1642. Furthest Building You Can Reach is tagged Greedy, Array and Heap (Priority Queue) on LeetCode.