Furthest Building You Can Reach (LeetCode 1642): Solution and Explanation
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
- For each i from 0 to n - 2, compute
climb = heights[i + 1] - heights[i]. Skip it if it is 0 or less. - Push the climb into a min-heap: for now it uses a ladder.
- If the heap holds more than
laddersclimbs, pop the smallest and subtract it frombricks. - If
bricksdrops below 0, returni. - 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
- 4 to 2 goes down: free.
- 2 to 7 is a climb of 5. It takes the only ladder: heap = [5].
- 7 to 6 goes down: free.
- 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.
- 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.
- 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) - 11class Solution {
2 public int furthestBuilding(int[] heights, int bricks, int ladders) {
3 PriorityQueue<Integer> heap = new PriorityQueue<>();
4 for (int i = 0; i < heights.length - 1; i++) {
5 int climb = heights[i + 1] - heights[i];
6 if (climb <= 0) {
7 continue;
8 }
9 heap.offer(climb);
10 if (heap.size() > ladders) {
11 bricks -= heap.poll();
12 if (bricks < 0) {
13 return i;
14 }
15 }
16 }
17 return heights.length - 1;
18 }
19}1class Solution {
2public:
3 int furthestBuilding(vector<int>& heights, int bricks, int ladders) {
4 priority_queue<int, vector<int>, greater<int>> heap;
5 for (int i = 0; i + 1 < (int)heights.size(); i++) {
6 int climb = heights[i + 1] - heights[i];
7 if (climb <= 0) {
8 continue;
9 }
10 heap.push(climb);
11 if ((int)heap.size() > ladders) {
12 bricks -= heap.top();
13 heap.pop();
14 if (bricks < 0) {
15 return i;
16 }
17 }
18 }
19 return (int)heights.size() - 1;
20 }
21};Time and space complexity
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.
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.