# Leetcode 1130 Minimum Cost Tree From Leaf Values

proheart

Given an array `arr` of positive integers, consider all binary trees such that:

• Each node has either 0 or 2 children;
• The values of `arr` correspond to the values of each leaf in an in-order traversal of the tree. _(Recall that a node is a leaf if and only if it has 0 children.)_
• The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree respectively.

Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node.  It is guaranteed this sum fits into a 32-bit integer.

Example 1:

Input: arr = [6,2,4]
Output: 32
Explanation:
There are two possible trees. The first has non-leaf node sum 36, and the second has non-leaf node sum 32.

Constraints:

• `2 <= arr.length <= 40`
• `1 <= arr[i] <= 15`
• It is guaranteed that the answer fits into a 32-bit signed integer (ie. it is less than `2^31`).

• 每个节点都有 0 个或是 2 个子节点。
• 数组 arr 中的值与树的中序遍历中每个叶节点的值一一对应。（一个节点有 0 个子节点，那么该节点为叶节点。）
• 每个非叶节点的值等于其左子树和右子树中叶节点的最大值的乘积。

``````dp[i][j] = min{dp[i][k] + dp[k+1][j] + largest[i][k] * largest[k+1][j]}
``````
``````public int mctFromLeafValues(int[] arr) {
int n = arr.length;
int[][] dp = new int[n][n];
for (int[] sub: dp) Arrays.fill(sub, Integer.MAX_VALUE);
int[][] large = new int[n][n];
for (int[] sub: large) Arrays.fill(sub, Integer.MAX_VALUE);
int sum = 0;
for (int i = 0; i < n; i++) {
dp[i][i] = arr[i];
large[i][i] = arr[i];
sum += arr[i];
}
for (int len = 2; len <= n; len++) {
for (int i = 0; i <= n - len; i++) {
int j = i + len - 1;
for (int k = i; k < j; k++) {
dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j] + large[i][k] * large[k + 1][j]);
large[i][j] = Math.max(large[i][k], large[k + 1][j]);
}
}
}
return dp[0][n - 1] - sum;
}``````

O(n)

``````[6,2,4,8] res = 0
[6,4,8]   res = 8
[6,8]     res = 8 + 24
[8]       res = 8 + 24 + 48``````

``````public int mctFromLeafValues1(int[] arr) {
Stack<Integer> st = new Stack<>();
st.push(Integer.MAX_VALUE);
int ans = 0;
for (int i = 0; i < arr.length; i++) {
while (st.peek() < arr[i]) {
int t = st.peek();
st.pop();
ans += t * Math.min(st.peek(), arr[i]);
}
st.push(arr[i]);
}
while (st.size() > 2) {
int t = st.peek();
st.pop();
ans += t * st.peek();
}
return ans;
}``````
https://www.jianshu.com/p/71f5d49292fc
https://github.com/wisdompeak/LeetCode/tree/master/Dynamic_Programming/1130.Minimum-Cost-Tree-From-Leaf-Values
https://www.acwing.com/solution/LeetCode/content/3996/

##### 来刷算法
Learn data structure and algorithm using java.
##### proheart

Developer, Java & Android

38 声望
20 粉丝
0 条评论