Furthest Building You Can Reach — LeetCode 1642 Python Solution

MediumGreedyArrayHeap (Priority Queue)
Problem
#1642
Reading time
3 min

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

Python
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) - 1

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview