Furthest Building You Can Reach (LeetCode 1642): Solution and Explanation

Medium
Array
Greedy
Heap Priority Queue

Walk along a row of buildings with a supply of bricks and ladders. Each upward step costs either one ladder or as many bricks as the climb; find the furthest building you can reach.

Intuition

A ladder covers a climb of any size, while bricks pay exactly the climb. So a ladder saves the most bricks when it sits on a big climb.

You do not need to decide in advance. Tentatively put a ladder on every climb and keep those climbs in a min-heap.

As soon as you have used one ladder more than you own, take back the ladder from the smallest climb in the heap and pay that climb with bricks instead. The heap always holds the largest climbs seen so far.

The first time the bricks go negative, the current building is as far as any plan can go.

Approach: Min-heap of laddered climbs

  1. For each i from 0 to n - 2, compute climb = heights[i + 1] - heights[i]. Skip it if it is 0 or less.
  2. Push the climb into a min-heap: for now it uses a ladder.
  3. If the heap holds more than ladders climbs, pop the smallest and subtract it from bricks.
  4. If bricks drops below 0, return i.
  5. If the loop finishes, every building is reachable: return n - 1.

Step-by-step example

heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
  1. 4 to 2 goes down: free.
  2. 2 to 7 is a climb of 5. It takes the only ladder: heap = [5].
  3. 7 to 6 goes down: free.
  4. 6 to 9 is a climb of 3. The heap now has 2 climbs for 1 ladder, so the smallest (3) is paid with bricks. 2 bricks left, the ladder stays on the climb of 5.
  5. 9 to 14 is a climb of 5. Again one climb too many, so the smallest (5) moves to bricks, which needs 5 but only 2 remain. Stuck at building 4.
  6. Return 4.

Code: Python, Java, C++

1class Solution:
2    def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:
3        heap = []
4        for i in range(len(heights) - 1):
5            climb = heights[i + 1] - heights[i]
6            if climb <= 0:
7                continue
8            heapq.heappush(heap, climb)
9            if len(heap) > ladders:
10                bricks -= heapq.heappop(heap)
11                if bricks < 0:
12                    return i
13        return len(heights) - 1
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log L)

Each climb is pushed once and popped at most once, and the heap never holds more than L + 1 climbs, where L is the number of ladders.

Space

O(L)

The heap stores at most L + 1 climbs.

Other approaches

Binary search on the answer (time O(n log^2 n), space O(n))

Binary search the furthest index k. For a candidate k, sort the climbs in heights[0..k], put ladders on the L largest and check whether the rest fit in the bricks.

Max-heap of bricked climbs (time O(n log n), space O(n))

Pay every climb with bricks and push it into a max-heap. When bricks go negative, spend a ladder to refund the largest bricked climb. Stop when no ladders are left to refund with.

Common mistakes

  • Using ladders greedily on the first climbs. An early small climb then wastes a ladder that a later big climb needed.
  • Returning i + 1 when the bricks run out. The climb from i to i + 1 could not be paid, so the answer is i.
  • Pushing downhill steps (climb <= 0) into the heap, which wastes ladders on free steps.
  • Handling ladders = 0 as a special case that breaks: with the heap approach every climb is popped right away and paid with bricks.

Frequently asked questions

Why is it safe to move a ladder from an earlier climb?

The choice of ladder or bricks for a past climb only matters through the total bricks spent. Moving the ladder to a bigger climb never spends more bricks, so the heap's choice is optimal for every prefix.

Why a min-heap and not a max-heap?

The heap holds the climbs that currently have ladders. When one has to go, you want to give up the cheapest one to pay in bricks, which is the minimum.

Can bricks overflow?

No. Bricks start at most 10^9 and only go down, by at most 10^6 per step before the function returns.