Skip to content

Commit 6849085

Browse files
authored
Create 1962-remove-stones-to-minimize-the-total.js
1 parent 07e5641 commit 6849085

File tree

1 file changed

+87
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)