Furthest Building You Can Reach LeetCode solution in JavaScript

1
var furthestBuilding = function (heights, bricks, ladders) {
2
const heap = new MaxPriorityQueue({ priority: (x) => x });
3

4
let i;
5

6
for (i = 0; i < heights.length - 1; i++) {
7
if (heights[i] >= heights[i + 1]) continue;
8

9
const diff = heights[i + 1] - heights[i];
10

11
// if not enough bricks are left
12
if (diff > bricks) {
13
// if not enough ladders are left
14
if (ladders === 0) break;
15

16
// if the max bricks used at once > current jump
17
// replace the max bricks with a ladder and use those bricks for current jump
18
// else use ladder for the current jump
19
if (!heap.isEmpty() && heap.front().element > diff) {
20
bricks += heap.dequeue().element - diff;
21
heap.enqueue(diff);
22
}
23
ladders--;
24
} else {
25
// greedly use bricks when possible
26
bricks -= diff;
27
heap.enqueue(diff);
28
}
29
}
30
return i;
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0