原题目:https://leetcode-cn.com/problems/minimum-cost-tree-from-leaf-values/
思路:
单调栈
代码:
class Solution {
public:
int mctFromLeafValues(vector<int>& arr) {
stack<int> monostack;
int sum = 0;
for(int tmp : arr){
while(!monostack.empty() &&monostack.top() < tmp){
int t = monostack.top();monostack.pop();
if(monostack.size()){
sum += t*min(tmp,monostack.top());
}
else{
sum += t* tmp;
}
}
monostack.push(tmp);
}
while(monostack.size() > 1){
int t = monostack.top();
monostack.pop();
sum += t*monostack.top();
}
return sum;
}
};