Skip to content

Commit c2848ad

Browse files
authored
Create 1642-furthest-building-you-can-reach.js
1 parent 37e5e50 commit c2848ad

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
/**
2+
* @param {number[]} heights
3+
* @param {number} bricks
4+
* @param {number} ladders
5+
* @return {number}
6+
*/
7+
const furthestBuilding = function (heights, bricks, ladders) {
8+
const queue = new PriorityQueue()
9+
for (let i = 1; i < heights.length; ++i) {
10+
if (heights[i] > heights[i - 1]) {
11+
let diff = heights[i] - heights[i - 1]
12+
if (diff <= bricks) {
13+
bricks -= diff
14+
queue.push(diff)
15+
} else if (ladders > 0) {
16+
let max = queue.isEmpty() ? 0 : queue.pop()
17+
--ladders
18+
if (max > diff) {
19+
bricks = bricks + max - diff
20+
queue.push(diff)
21+
} else {
22+
queue.push(max)
23+
}
24+
} else {
25+
return i - 1
26+
}
27+
}
28+
}
29+
return heights.length - 1
30+
}
31+
class PriorityQueue {
32+
constructor(comparator = (a, b) => a > b) {
33+
this.heap = []
34+
this.top = 0
35+
this.comparator = comparator
36+
}
37+
size() {
38+
return this.heap.length
39+
}
40+
isEmpty() {
41+
return this.size() === 0
42+
}
43+
peek() {
44+
return this.heap[this.top]
45+
}
46+
push(...values) {
47+
values.forEach((value) => {
48+
this.heap.push(value)
49+
this.siftUp()
50+
})
51+
return this.size()
52+
}
53+
pop() {
54+
const poppedValue = this.peek()
55+
const bottom = this.size() - 1
56+
if (bottom > this.top) {
57+
this.swap(this.top, bottom)
58+
}
59+
this.heap.pop()
60+
this.siftDown()
61+
return poppedValue
62+
}
63+
replace(value) {
64+
const replacedValue = this.peek()
65+
this.heap[this.top] = value
66+
this.siftDown()
67+
return replacedValue
68+
}
69+
70+
parent = (i) => ((i + 1) >>> 1) - 1
71+
left = (i) => (i << 1) + 1
72+
right = (i) => (i + 1) << 1
73+
greater = (i, j) => this.comparator(this.heap[i], this.heap[j])
74+
swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])
75+
siftUp = () => {
76+
let node = this.size() - 1
77+
while (node > this.top && this.greater(node, this.parent(node))) {
78+
this.swap(node, this.parent(node))
79+
node = this.parent(node)
80+
}
81+
}
82+
siftDown = () => {
83+
let node = this.top
84+
while (
85+
(this.left(node) < this.size() && this.greater(this.left(node), node)) ||
86+
(this.right(node) < this.size() && this.greater(this.right(node), node))
87+
) {
88+
let maxChild =
89+
this.right(node) < this.size() &&
90+
this.greater(this.right(node), this.left(node))
91+
? this.right(node)
92+
: this.left(node)
93+
this.swap(node, maxChild)
94+
node = maxChild
95+
}
96+
}
97+
}

0 commit comments

Comments
 (0)