Furthest Building You Can Reach

Problem Summary

Key Observations

Approach Taken

Why This Works

Main Concepts Used

Time & Space Complexity

Code

class Solution:
    def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:
        # heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2

        # 4->12 - ladder
        # 12->2 - nothing
        # 2->7  - bricks
        # 7->3  - nothing
        # we are out of ladders but we have 10 bricks
        # whats the smallest jump we can replace with bricks 2->7 = 5 bricks
        # 3->18 - ladder now
        # 20->3 - nothing
        # we stop here because:
        #   - cant replace a ladder with remaining bricks

        smallestLadderUsage = [] # 8,15

        prevHeight = None
        for i, currentHeight in enumerate(heights):
            if prevHeight is not None and currentHeight > prevHeight:
                diffToClimb = currentHeight - prevHeight # 8, 5, 2
                if ladders: # try ladders first
                    ladders -= 1
                    heapq.heappush(smallestLadderUsage, diffToClimb)
                else:
                    if smallestLadderUsage and smallestLadderUsage[0] <= bricks and diffToClimb > smallestLadderUsage[0]:
                        bricks -= heapq.heappop(smallestLadderUsage)
                        heapq.heappush(smallestLadderUsage, diffToClimb)
                    elif diffToClimb <= bricks:
                        bricks -= diffToClimb
                    else:
                        return i - 1
            prevHeight = currentHeight
        return i

Common Mistakes / Things I Got Stuck On