File tree 2 files changed +42
-1
lines changed
2 files changed +42
-1
lines changed Original file line number Diff line number Diff line change 1
- # 1,145 LeetCode solutions in JavaScript
1
+ # 1,146 LeetCode solutions in JavaScript
2
2
3
3
[ https://leetcodejavascript.com ] ( https://leetcodejavascript.com )
4
4
891
891
1125|[ Smallest Sufficient Team] ( ./solutions/1125-smallest-sufficient-team.js ) |Hard|
892
892
1128|[ Number of Equivalent Domino Pairs] ( ./solutions/1128-number-of-equivalent-domino-pairs.js ) |Easy|
893
893
1129|[ Shortest Path with Alternating Colors] ( ./solutions/1129-shortest-path-with-alternating-colors.js ) |Medium|
894
+ 1130|[ Minimum Cost Tree From Leaf Values] ( ./solutions/1130-minimum-cost-tree-from-leaf-values.js ) |Medium|
894
895
1137|[ N-th Tribonacci Number] ( ./solutions/1137-n-th-tribonacci-number.js ) |Easy|
895
896
1143|[ Longest Common Subsequence] ( ./solutions/1143-longest-common-subsequence.js ) |Medium|
896
897
1161|[ Maximum Level Sum of a Binary Tree] ( ./solutions/1161-maximum-level-sum-of-a-binary-tree.js ) |Medium|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 1130. Minimum Cost Tree From Leaf Values
3
+ * https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given an array arr of positive integers, consider all binary trees such that:
7
+ * - Each node has either 0 or 2 children;
8
+ * - The values of arr correspond to the values of each leaf in an in-order traversal of the tree.
9
+ * - The value of each non-leaf node is equal to the product of the largest leaf value in its left
10
+ * and right subtree, respectively.
11
+ *
12
+ * Among all possible binary trees considered, return the smallest possible sum of the values of
13
+ * each non-leaf node. It is guaranteed this sum fits into a 32-bit integer.
14
+ *
15
+ * A node is a leaf if and only if it has zero children.
16
+ */
17
+
18
+ /**
19
+ * @param {number[] } arr
20
+ * @return {number }
21
+ */
22
+ var mctFromLeafValues = function ( arr ) {
23
+ const stack = [ ] ;
24
+ let result = 0 ;
25
+
26
+ for ( const value of arr ) {
27
+ while ( stack . length && stack [ stack . length - 1 ] <= value ) {
28
+ const small = stack . pop ( ) ;
29
+ result += small * Math . min ( stack [ stack . length - 1 ] || Infinity , value ) ;
30
+ }
31
+ stack . push ( value ) ;
32
+ }
33
+
34
+ while ( stack . length > 1 ) {
35
+ const small = stack . pop ( ) ;
36
+ result += small * stack [ stack . length - 1 ] ;
37
+ }
38
+
39
+ return result ;
40
+ } ;
You can’t perform that action at this time.
0 commit comments