Skip to content

Commit 6016bee

Browse files
authored
Update 1353-maximum-number-of-events-that-can-be-attended.js
1 parent 86fb8c6 commit 6016bee

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed

1353-maximum-number-of-events-that-can-be-attended.js

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

0 commit comments

Comments
 (0)