Skip to content

Commit 8baaf7c

Browse files
authored
Update 1642-furthest-building-you-can-reach.js
1 parent 6cb758a commit 8baaf7c

File tree

1 file changed

+11
-22
lines changed

1 file changed

+11
-22
lines changed

1642-furthest-building-you-can-reach.js

Lines changed: 11 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,30 +4,19 @@
44
* @param {number} ladders
55
* @return {number}
66
*/
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-
}
7+
const furthestBuilding = function(heights, bricks, ladders) {
8+
const pq = new PriorityQueue((a, b) => a < b)
9+
const len = heights.length
10+
for(let i = 0; i < len - 1; i++) {
11+
const diff = heights[i + 1] - heights[i]
12+
if(diff > 0) pq.push(diff)
13+
if(pq.size() > ladders) {
14+
bricks -= pq.pop()
2715
}
16+
if(bricks < 0) return i
2817
}
29-
return heights.length - 1
30-
}
18+
return len - 1
19+
};
3120
class PriorityQueue {
3221
constructor(comparator = (a, b) => a > b) {
3322
this.heap = []

0 commit comments

Comments
 (0)