Skip to content

Commit e59b5fb

Browse files
committed
Add solution #1130
1 parent b1a6163 commit e59b5fb

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,145 LeetCode solutions in JavaScript
1+
# 1,146 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -891,6 +891,7 @@
891891
1125|[Smallest Sufficient Team](./solutions/1125-smallest-sufficient-team.js)|Hard|
892892
1128|[Number of Equivalent Domino Pairs](./solutions/1128-number-of-equivalent-domino-pairs.js)|Easy|
893893
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|
894895
1137|[N-th Tribonacci Number](./solutions/1137-n-th-tribonacci-number.js)|Easy|
895896
1143|[Longest Common Subsequence](./solutions/1143-longest-common-subsequence.js)|Medium|
896897
1161|[Maximum Level Sum of a Binary Tree](./solutions/1161-maximum-level-sum-of-a-binary-tree.js)|Medium|
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
};

0 commit comments

Comments
 (0)