What it teaches: Deciding in hindsight: give ladders to the largest climbs so far by keeping them in a min-heap, and pay bricks for the smallest.
Practise it on judges as “Furthest Building You Can Reach”.
The problem
Walking from building 0, climbing up from height h[i] to h[i+1] needs either h[i+1] − h[i] bricks or one ladder; going down or level is free. Return the furthest building index you can reach.
For each climb d > 0: push d. If the heap holds more than ladders climbs, pop the smallest and pay with bricks. If bricks go negative, return i.
Approach 1
import java.util.PriorityQueue;
class Solution {
public int furthestBuilding(int[] heights, int bricks, int ladders) {
PriorityQueue<Integer> climbs = new PriorityQueue<>();
for (int i = 0; i < heights.length - 1; i++) {
int d = heights[i + 1] - heights[i];
if (d <= 0) continue;
climbs.offer(d);
if (climbs.size() > ladders) bricks -= climbs.poll();
if (bricks < 0) return i;
}
return heights.length - 1;
}
}
Verdict: One pass, greedy with a heap.
Before you submit
Edge cases and common mistakes
Test these inputs
No climbs at all
Zero ladders
Enough bricks for everything
Mistakes people make
Using ladders greedily on the first climbs you see.
Interview
Follow-up questions
Why is it safe to move a ladder from one climb to another after the fact?