1public int furthestBuilding(int[] heights, int bricks, int ladders) {
2 // Min-heap of climbs where we used bricks
3 PriorityQueue<Integer> heap = new PriorityQueue<>();
4 int bricksUsed = 0;
5
6 for (int i = 0; i < heights.length - 1; i++) {
7 int climb = heights[i + 1] - heights[i];
8
9 if (climb <= 0) {
10 continue; // no climb needed
11 }
12
13 // Use bricks for this climb
14 bricksUsed += climb;
15 heap.offer(climb);
16
17 if (bricksUsed > bricks) {
18 // Exceeded bricks, need a ladder
19 if (ladders == 0) {
20 return i; // can't proceed
21 }
22
23 // Replace smallest climb with a ladder
24 int smallest = heap.poll();
25 bricksUsed -= smallest;
26 ladders--;
27 }
28 }
29
30 return heights.length - 1;
31}