Skip to content

Commit 694b116

Browse files
authored
Create 1167-minimum-cost-to-connect-sticks.js
1 parent 67949d0 commit 694b116

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* @param {number[]} sticks
3+
* @return {number}
4+
*/
5+
const connectSticks = function(sticks) {
6+
if (sticks.length < 1) return 0
7+
let size = sticks.length - 1
8+
let i = Math.floor(sticks.length / 2)
9+
for (; i >= 0; i--) {
10+
heapify(sticks, i, size)
11+
}
12+
let cost = 0
13+
while (size >= 1) {
14+
const temp = sticks[0]
15+
sticks[0] = sticks[size--]
16+
heapify(sticks, 0, size)
17+
sticks[0] = sticks[0] + temp
18+
cost += sticks[0]
19+
heapify(sticks, 0, size)
20+
}
21+
return cost
22+
}
23+
const heapify = (arr, index, size) => {
24+
let smallest = index
25+
let l = index * 2 + 1
26+
let r = index * 2 + 2
27+
if (l <= size && arr[l] < arr[smallest]) {
28+
smallest = l
29+
}
30+
if (r <= size && arr[r] < arr[smallest]) {
31+
smallest = r
32+
}
33+
if (smallest != index) {
34+
swap(arr, index, smallest)
35+
heapify(arr, smallest, size)
36+
}
37+
}
38+
const swap = (arr, i, j) => {
39+
const temp = arr[i]
40+
arr[i] = arr[j]
41+
arr[j] = temp
42+
}

0 commit comments

Comments
 (0)