Furthest Building You Can Reach - Problem

You are given an integer array heights representing the heights of buildings, along with a certain number of bricks and ladders.

You start your journey from building 0 and move to the next building by possibly using bricks or ladders.

While moving from building i to building i+1 (0-indexed):

  • If the current building's height is greater than or equal to the next building's height, you do not need a ladder or bricks.
  • If the current building's height is less than the next building's height, you can either use one ladder or (h[i+1] - h[i]) bricks.

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

Input & Output

Example 1 — Basic Case
$ Input: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
Output: 4
💡 Note: Starting at building 0, we can reach building 4: gaps are -2 (free), +5 (use 5 bricks), -1 (free), +3 (use ladder). At gap +5 to building 5, we need bricks but have none left.
Example 2 — Use All Resources
$ Input: heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2
Output: 7
💡 Note: Use ladders for gaps +8 and +15, use 10 bricks for gaps +5 and +5. Can reach building 7, but gap +16 to building 8 is too large.
Example 3 — All Decreasing
$ Input: heights = [14,3,19,3], bricks = 17, ladders = 0
Output: 3
💡 Note: Gap -11 (free), +16 (use 16 bricks), -16 (free). We can reach the end using only bricks for the one upward gap.

Constraints

  • 1 ≤ heights.length ≤ 105
  • 1 ≤ heights[i] ≤ 106
  • 0 ≤ bricks ≤ 106
  • 0 ≤ ladders ≤ heights.length

Visualization

Tap to expand
Furthest Building You Can Reach INPUT 4 2 7 6 9 14 12 0 1 2 3 4 5 6 heights = [4,2,7,6,9,14,12] bricks = 5 ladders = 1 ALGORITHM STEPS 1 Init Min-Heap Track climbs using ladder 2 Process Each Jump Skip if going down 3 Use Ladder First Push diff to heap 4 Swap if Needed Replace min with bricks Climb Differences: 0--1:0 1--2:5 2--3:0 3--4:3 4--5:5 Heap: [3] (ladder), Bricks: 5-5=0 FINAL RESULT 4 2 7 6 9 14 OUTPUT 4 Reached building index 4 Used: 5 bricks + 1 ladder Cannot reach index 5 Key Insight: Use ladders for the LARGEST climbs. The min-heap tracks climbs where ladders are used. When heap size exceeds ladder count, pop the smallest climb and use bricks instead. This greedy approach ensures optimal resource usage: ladders for big jumps, bricks for small ones. TutorialsPoint - Furthest Building You Can Reach | Greedy with Min-Heap Approach Reachable Final Blocked
Asked in
Facebook 35 Google 28 Amazon 22
86.0K Views
Medium Frequency
~25 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen