File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments