Skip to content

Commit 31587c5

Browse files
authored
Update 1675-minimize-deviation-in-array.js
1 parent 0b721b6 commit 31587c5

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

1675-minimize-deviation-in-array.js

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,97 @@
1+
class PQ {
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[]} nums
70+
* @return {number}
71+
*/
72+
const minimumDeviation = function(nums) {
73+
const pq = new PQ((a, b) => a > b)
74+
let min = Infinity
75+
for(const e of nums) {
76+
const tmp = e % 2 === 1 ? e * 2: e
77+
pq.push(tmp)
78+
min = Math.min(min, tmp)
79+
}
80+
let res = Infinity
81+
while(pq.peek() % 2 === 0) {
82+
const e = pq.pop()
83+
res = Math.min(res, e - min)
84+
min = Math.min(min, e / 2)
85+
pq.push(e / 2)
86+
}
87+
if(pq.size()) {
88+
res = Math.min(res, pq.peek() - min)
89+
}
90+
return res
91+
};
92+
93+
// another
94+
195
/**
296
* @param {number[]} nums
397
* @return {number}

0 commit comments

Comments
 (0)