File tree 1 file changed +12
-11
lines changed
scripts/algorithms/M/Minimum Cost Tree From Leaf Values 1 file changed +12
-11
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 193 ms (Top 7.04%) | Memory: 48.6 MB (Top 15.49%)
1
2
var mctFromLeafValues = function ( arr ) {
2
3
const dp = [ ] ;
3
4
4
5
for ( let i = 0 ; i < arr . length ; i ++ ) {
5
6
dp [ i ] = [ ] ;
6
7
}
7
-
8
+
8
9
return treeBuilder ( 0 , arr . length - 1 ) ;
9
-
10
+
10
11
function treeBuilder ( start , end ) {
11
-
12
+
12
13
if ( start == end ) {
13
14
return 0 ;
14
15
}
15
-
16
+
16
17
if ( dp [ start ] [ end ] ) {
17
18
return dp [ start ] [ end ] ;
18
19
}
19
-
20
+
20
21
let min = Number . MAX_VALUE ;
21
-
22
+
22
23
for ( let i = start ; i < end ; i ++ ) {
23
24
const left = treeBuilder ( start , i ) ;
24
25
const right = treeBuilder ( i + 1 , end ) ;
25
-
26
+
26
27
const maxLeft = Math . max ( ...arr . slice ( start , i + 1 ) ) ;
27
28
const maxRight = Math . max ( ...arr . slice ( i + 1 , end + 1 ) ) ;
28
-
29
+
29
30
const rootVal = maxLeft * maxRight ;
30
-
31
+
31
32
min = Math . min ( min , rootVal + left + right ) ;
32
33
33
34
}
34
-
35
+
35
36
dp [ start ] [ end ] = min ;
36
37
return min ;
37
38
}
38
- } ;
39
+ } ;
You can’t perform that action at this time.
0 commit comments