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
Understanding the Visualization
1
Input
Building heights array with limited bricks and ladders
2
Process
Use greedy strategy: ladders for biggest gaps, bricks for smallest
3
Output
Maximum building index reachable
Key Takeaway
🎯 Key Insight: Save ladders for the largest gaps by using a min-heap to track optimal resource allocation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code