Furthest Building You Can Reach - Problem
Imagine you're a daredevil parkour athlete navigating a cityscape filled with buildings of varying heights! ๐ข
You start at building 0 and want to reach as far as possible by jumping from one building to the next. Here's the challenge:
- If the next building is lower or equal height, you can jump freely ๐ฆ
- If the next building is taller, you need help:
- Use a
ladder(works for any height difference) ๐ช - OR use
bricksequal to the height difference ๐งฑ
- Use a
Given an array heights representing building heights, plus your limited supply of bricks and ladders, find the furthest building index you can reach using optimal strategy!
Goal: Maximize the distance traveled by using your resources wisely.
Input & Output
example_1.py โ Basic Example
$
Input:
heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
โบ
Output:
4
๐ก Note:
Starting at building 0 (height 4): Go to building 1 (height 2) - no resources needed. Go to building 2 (height 7) - use 5 bricks. Go to building 3 (height 6) - no resources needed. Go to building 4 (height 9) - use 1 ladder. Cannot reach building 5 (height 14) as we need 5 more units but have 0 bricks and 0 ladders.
example_2.py โ Ladder Heavy
$
Input:
heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2
โบ
Output:
7
๐ก Note:
We can optimally use ladders for the two largest gaps (height differences of 8 and 15) and bricks for smaller gaps. This allows us to reach building 7 before getting stuck.
example_3.py โ All Decreasing
$
Input:
heights = [14,3,19,3], bricks = 17, ladders = 0
โบ
Output:
3
๐ก Note:
From 14โ3 (no resources), 3โ19 (use 16 bricks), 19โ3 (no resources). We can reach the end with bricks to spare.
Constraints
- 1 โค heights.length โค 105
- 1 โค heights[i] โค 106
- 0 โค bricks โค 109
- 0 โค ladders โค heights.length
- Note: Building indices are 0-based
Visualization
Tap to expand
Understanding the Visualization
1
Initial Strategy
Start by using ladders for every upward jump - they're the most flexible resource
2
Resource Tracking
Keep a min-heap of all height differences where you've used ladders
3
Smart Reallocation
When you run out of ladders, take back the ladder from the smallest gap and use bricks there instead
4
Optimal Assignment
Now use that freed ladder for the current (likely larger) gap - always keeping ladders for biggest obstacles
Key Takeaway
๐ฏ Key Insight: The optimal strategy is counter-intuitive - don't greedily assign ladders as you encounter gaps. Instead, use a priority queue to continuously optimize and ensure ladders are always used for the largest height differences encountered so far.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code