Skip to content

Commit a9206f3

Browse files
authored
Update 2054-two-best-non-overlapping-events.js
1 parent d234e83 commit a9206f3

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

2054-two-best-non-overlapping-events.js

+88
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,91 @@ const maxTwoEvents = function(events) {
2828
return dp[idx][cnt]
2929
}
3030
};
31+
32+
// another
33+
34+
/**
35+
* @param {number[][]} events
36+
* @return {number}
37+
*/
38+
const maxTwoEvents = function(events) {
39+
const n = events.length, { max } = Math
40+
let res = 0, maxVal = 0;
41+
const pq = new PriorityQueue((a, b) => a[0] < b[0]);
42+
events.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0])
43+
for (let e of events) {
44+
for(; !pq.isEmpty() && pq.peek()[0] < e[0]; pq.pop())
45+
maxVal = max(maxVal, pq.peek()[1]);
46+
res = max(res, maxVal + e[2]);
47+
pq.push([e[1], e[2]]);
48+
}
49+
return res;
50+
};
51+
52+
class PriorityQueue {
53+
constructor(comparator = (a, b) => a > b) {
54+
this.heap = []
55+
this.top = 0
56+
this.comparator = comparator
57+
}
58+
size() {
59+
return this.heap.length
60+
}
61+
isEmpty() {
62+
return this.size() === 0
63+
}
64+
peek() {
65+
return this.heap[this.top]
66+
}
67+
push(...values) {
68+
values.forEach((value) => {
69+
this.heap.push(value)
70+
this.siftUp()
71+
})
72+
return this.size()
73+
}
74+
pop() {
75+
const poppedValue = this.peek()
76+
const bottom = this.size() - 1
77+
if (bottom > this.top) {
78+
this.swap(this.top, bottom)
79+
}
80+
this.heap.pop()
81+
this.siftDown()
82+
return poppedValue
83+
}
84+
replace(value) {
85+
const replacedValue = this.peek()
86+
this.heap[this.top] = value
87+
this.siftDown()
88+
return replacedValue
89+
}
90+
91+
parent = (i) => ((i + 1) >>> 1) - 1
92+
left = (i) => (i << 1) + 1
93+
right = (i) => (i + 1) << 1
94+
greater = (i, j) => this.comparator(this.heap[i], this.heap[j])
95+
swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])
96+
siftUp = () => {
97+
let node = this.size() - 1
98+
while (node > this.top && this.greater(node, this.parent(node))) {
99+
this.swap(node, this.parent(node))
100+
node = this.parent(node)
101+
}
102+
}
103+
siftDown = () => {
104+
let node = this.top
105+
while (
106+
(this.left(node) < this.size() && this.greater(this.left(node), node)) ||
107+
(this.right(node) < this.size() && this.greater(this.right(node), node))
108+
) {
109+
let maxChild =
110+
this.right(node) < this.size() &&
111+
this.greater(this.right(node), this.left(node))
112+
? this.right(node)
113+
: this.left(node)
114+
this.swap(node, maxChild)
115+
node = maxChild
116+
}
117+
}
118+
}

0 commit comments

Comments
 (0)