Skip to content

Commit a2be85f

Browse files
authored
Create 2611-mice-and-cheese.js
1 parent 1fa73a6 commit a2be85f

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed

2611-mice-and-cheese.js

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

0 commit comments

Comments
 (0)