LeetCode 1130 Minimum Cost Tree From Leaf Values 思维
Given an array arr
of positive integers, consider all binary trees such that:
- Each node has either
0
or2
children; - The values of
arr
correspond to the values of each leaf in an in-order traversal of the tree. - 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.
A node is a leaf if and only if it has zero children.
Solution
每个非叶子节点的值是左右子树最大值的乘积。考虑相邻两个元素 \(a,b\),由于我们仅需要保留每棵子树的最大值,每次把较小值 \(pop\) 出去。因此此时移除一个较小的元素 \(a (a\leq b)\),所需要的花费是 \(a\cdot b\),所以每次 \(a\) 都是和一个较大的数相组合,然后 remove. 为了最小化 \(a\cdot b\),即最小化 \(b\)。 而 \(b\) 有两个选择,左边或者右边,因此
\[a\cdot \min(left,right)
\]
点击查看代码
class Solution {
private:
vector<int> sk;
int ans=0;
public:
int mctFromLeafValues(vector<int>& arr) {
int n = arr.size();sk.push_back(99999);
for(auto ele:arr){
while(sk.back()<=ele){
int middle = sk.back();
sk.pop_back();
ans += middle * min(ele,sk.back());
}
sk.push_back(ele);
}
for(int i=1;i<sk.size()-1;i++){
ans += sk[i]*sk[i+1];
}
return ans;
}
};