Skip to content

Commit 05b456f

Browse files
authored
Create 1199-minimum-time-to-build-blocks.js
1 parent d56dd3e commit 05b456f

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

1199-minimum-time-to-build-blocks.js

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* @param {number[]} blocks
3+
* @param {number} split
4+
* @return {number}
5+
*/
6+
const minBuildTime = function (blocks, split) {
7+
const minHeap = new MinHeap()
8+
blocks.forEach((block) => minHeap.push(block))
9+
while (minHeap.size() > 1) {
10+
minHeap.pop()
11+
minHeap.push(minHeap.pop() + split)
12+
}
13+
return minHeap.pop()
14+
}
15+
16+
class MinHeap {
17+
constructor() {
18+
this.store = []
19+
}
20+
size() {
21+
return this.store.length
22+
}
23+
push(value) {
24+
this.store.push(value)
25+
this.heapifyUp(this.store.length - 1)
26+
}
27+
pop() {
28+
if (this.store.length < 2) return this.store.pop()
29+
let result = this.store[0]
30+
this.store[0] = this.store.pop()
31+
this.heapifyDown(0)
32+
return result
33+
}
34+
heapifyUp(child) {
35+
const parent = Math.floor((child - 1) / 2)
36+
if (child && this.store[child] < this.store[parent]) {
37+
const temp = this.store[child]
38+
this.store[child] = this.store[parent]
39+
this.store[parent] = temp
40+
this.heapifyUp(parent)
41+
}
42+
}
43+
heapifyDown(parent) {
44+
const childs = [1, 2]
45+
.map((n) => parent * 2 + n)
46+
.filter((n) => n < this.store.length)
47+
let child = childs[0]
48+
if (childs[1] && this.store[childs[1]] < this.store[child]) {
49+
child = childs[1]
50+
}
51+
if (child && this.store[child] < this.store[parent]) {
52+
const temp = this.store[child]
53+
this.store[child] = this.store[parent]
54+
this.store[parent] = temp
55+
this.heapifyDown(child)
56+
}
57+
}
58+
}

0 commit comments

Comments
 (0)