Solution
1/**
2 * @param {number[]} heights
3 * @param {number} bricks
4 * @param {number} ladders
5 * @return {number}
6 */
7const furthestBuilding = (heights, bricks, ladders) => {
8 let N = heights.length;
9 // MinPriorityQueue (min-heap) to store the height differences we need to overcome
10 let heap = new MinPriorityQueue();
11
12 for (let i = 1; i < N;h i++) {
13 let curr = heights[i - 1];
14 let next = heights[i];
15 let diff = next - curr;
16
17 // when climbing up, we have to decide whether to use bricks or ladders.
18 if (diff > 0) {
19 // store into min heap
20 heap.enqueue(diff);
21
22 // if the heap size exceeds the number of ladders available, we need to start using bricks, also means we have encountered more gaps than we have ladders to cover
23 // note: when we have more in heap than ladders, that is when to decide whether we can continue by checking the smallest height.
24 if (heap.size() > ladders) {
25 let smallestHeight = heap.dequeue().element;
26
27 if (bricks >= smallestHeight) {
28 bricks -= smallestHeight;
29 } else {
30 // if bricks cant cover the smallest height, that is the furtherest we can go.
31 return i - 1;
32 }
33 }
34 }
35 }
36
37 return N - 1;
38}