Python coding

Farthest rooftop with bricks and ladders

Rooftops stand in a row with heights heights. You start on rooftop 0 and move right one rooftop at a time. Stepping to a rooftop that is not taller is free; climbing up by d costs either d bricks or one ladder, which covers any climb. You have bricks bricks and ladders ladders, and each brick and each ladder can be used only once. Return the index of the farthest rooftop you can reach if you spend them as well as possible.

Aim for O(n log L) with L ladders, instead of re-planning the whole route at every step.

Besides the tests, one large input (8,000 rising rooftops) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • farthest_rooftop([4,2,7,6,9,14,12], 5, 1) → 4
  • farthest_rooftop([4,12,2,7,3,18,20,3,19], 10, 2) → 7
  • farthest_rooftop([14,3,19,3], 17, 0) → 3
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

You don't have to choose on the spot. Looking back from any rooftop, the best plan put the ladders on the largest climbs so far and paid the rest in bricks.

Hint 2

Push every climb into a min-heap. When it holds more climbs than ladders, pop the smallest and pay it in bricks; the first time bricks go negative, you are stuck on the current rooftop.

Solution and why it works
pythonO(n log L), L = ladders · O(L)
import heapq


def farthest_rooftop(heights: list[int], bricks: int, ladders: int) -> int:
    ladder_climbs = []                       # min-heap: the climbs the ladders cover so far
    for i in range(len(heights) - 1):
        climb = heights[i + 1] - heights[i]
        if climb <= 0:
            continue                         # going down or level is free
        heapq.heappush(ladder_climbs, climb)
        if len(ladder_climbs) > ladders:
            bricks -= heapq.heappop(ladder_climbs)   # the smallest climb is paid in bricks
            if bricks < 0:
                return i
    return len(heights) - 1

Looking back from any rooftop, the cheapest plan always puts the ladders on the largest climbs so far. The min-heap holds exactly those climbs; when a new climb makes it one too many, its root, the smallest of them, is the one to pay in bricks, chosen with hindsight. Each climb costs O(log L). The trap is deciding on the spot: bricks first can waste them on a climb a ladder should take, ladders first can spend one on a one-step climb.