Furthest Building You Can Reach

Use bricks for short climbs and ladders for tall ones, swapping greedily to maximize reach.

MEDIUM
Free
heap
priority-queue
greedy
davidtoure

By @davidtoure

April 20, 2026

·

Updated May 18, 2026

470 views

2

4.3 (14)

I had this on a Bloomberg onsite and the interviewer's only hint was "do not commit a ladder until you have to". That hint hides the entire algorithm: a min-heap of the climbs you have spent ladders on, and the moment you exceed your ladder budget you cash in the SMALLEST one for bricks. The catalog covers Min-Heap basics, but it skipped this resource-allocation gem.

Furthest Building You Can Reach

You are given an integer array heights representing the heights of buildings, some bricks, and some ladders. You start at building 0 (the leftmost). At each move, you may proceed from building i to building i + 1. While moving from i to i + 1:

  • If heights[i] >= heights[i + 1], you can jump down for free.
  • If heights[i] < heights[i + 1], you climb up by heights[i + 1] - heights[i]. To make this climb you may use either:
    • A single ladder (handles any height), or
    • Bricks equal to the difference.

Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally.

Examples

Example 1:

  • Input: heights = [4, 2, 7, 6, 9, 14, 12], bricks = 5, ladders = 1
  • Output: 4
  • Explanation: Drop from 4 to 2 (free), climb 2 -> 7 (use 5 bricks), drop 7 -> 6 (free), climb 6 -> 9 (use the ladder). Now we are at index 4. The next climb 9 -> 14 needs 5 bricks but we have none. Stop at index 4.

Example 2:

  • Input: heights = [4, 12, 2, 7, 3, 18, 20, 3, 19], bricks = 10, ladders = 2
  • Output: 7
  • Explanation: One optimal path uses ladders for 12 -> 18 and 18 -> 20, and bricks across the smaller climbs.

Example 3:

  • Input: heights = [14, 3, 19, 3], bricks = 17, ladders = 0
  • Output: 3
  • Explanation: Drop, climb 3 -> 19 with 16 bricks, drop. We end at the last building.

Example 4:

  • Input: heights = [1, 5, 1, 2, 3, 4, 10000], bricks = 7, ladders = 1
  • Output: 6
  • Explanation: Use 4 bricks for 1 -> 5, three more bricks for 1 -> 2 -> 3 -> 4, and save the ladder for the giant 4 -> 10000 jump.

Constraints

  • 1 <= heights.length <= 10^5.
  • 1 <= heights[i] <= 10^6.
  • 0 <= bricks <= 10^9.
  • 0 <= ladders <= heights.length.

Follow-up

Why is the greedy correct? Sketch: the ladders should always cover the LARGEST climbs. We discover climbs in left-to-right order, so we tentatively spend ladders on every climb (storing the climb height in a min-heap). The moment we have spent more than ladders of them, the smallest one in the heap is converted to bricks. When bricks run out, we are stuck.

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems