SDE & MLE Prep

1642. Furthest Building You Can Reach

Problem

Walk from building 0 to the right. Stepping down or level is free; stepping up by d costs either one ladder or d bricks. Using your bricks and ladders optimally, return the furthest building index you can reach.

Example: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1 → 4

Constraints: n ≤ 10⁵.

Use ladders for the largest climbs. Push every climb into a min-heap; when the heap exceeds ladders, the smallest climb gets paid with bricks instead. Stop when bricks go negative.

Complexity: O(n log ladders).

class Solution:
    def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:
        h = []
        for i in range(len(heights) - 1):
            d = heights[i + 1] - heights[i]
            if d <= 0:
                continue
            heappush(h, d)
            if len(h) > ladders:
                bricks -= heappop(h)
                if bricks < 0:
                    return i
        return len(heights) - 1