Skip to content

Commit 21876f4

Browse files
authored
Create 2530-maximal-score-after-applying-k-operations.js
1 parent d602111 commit 21876f4

File tree

1 file changed

+86
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)