Skip to content

Commit c90fd46

Browse files
authored
Merge pull request #3555 from aadil42/patch-93
Create 1642-furthest-building-you-can-reach.js
2 parents 91c728a + 9ad9e79 commit c90fd46

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* MaxPriorityQueue
3+
* Time O(n*log(n)) | Space O(n)
4+
* https://leetcode.com/problems/furthest-building-you-can-reach/
5+
* @param {number[]} heights
6+
* @param {number} bricks
7+
* @param {number} ladders
8+
* @return {number}
9+
*/
10+
var furthestBuilding = function(heights, bricks, ladders) {
11+
12+
const maxPriorityQueue = new MaxPriorityQueue({
13+
compare: (a, b) => {
14+
return b - a;
15+
}
16+
});
17+
18+
let i = 0;
19+
20+
while (i < heights.length - 1) {
21+
const diff = heights[i + 1] - heights[i];
22+
23+
if (diff <= 0) {
24+
i++;
25+
continue;
26+
}
27+
28+
bricks -= diff;
29+
maxPriorityQueue.enqueue(diff);
30+
31+
if (bricks < 0) {
32+
if (!ladders) return i;
33+
ladders -= 1;
34+
bricks += maxPriorityQueue.dequeue();
35+
}
36+
i++;
37+
}
38+
39+
return heights.length - 1;
40+
};

0 commit comments

Comments
 (0)