zoukankan      html  css  js  c++  java
  • 单调栈 leetcode 1130.

    参考链接:

    https://blog.csdn.net/qq_17550379/article/details/97020009

    https://blog.csdn.net/qq_17550379/article/details/86519771

    题意:一颗二叉树每个结点只能有0个或2个孩子,arr里面是这颗树的中序遍历中的所有的叶子结点,每个非叶结点的值等于其左子树和右子树中叶结点的最大值的乘积,返回最小的非叶结点的值的可能总和。

    如:上面的例子中,(左)6*2 + 6*4 = 12 + 24 = 36 , (右)6*4 + 2*4 = 24 + 8 = 32

    故,最后答案是32

     再举一个例子:arr = [6, 2, 4, 5, 7, 8]

    class Solution {
    public:
        int mctFromLeafValues(vector<int>& arr) {
            stack<int> st;
            st.push(INT_MAX);
            int res = 0;
            
            for(int a : arr){
                while(st.top() <= a){
                    int little = st.top();
                    st.pop();
                    res += little * min(st.top(), a);
                }
                st.push(a);
            }
            
            while(st.size()>2){
                //栈底到栈顶为从大到小排序,将它们从栈顶开始,两两相乘
                int r = st.top();
                st.pop();
                res += r * st.top();   
            }
            return res;
        }
    };
  • 相关阅读:
    springMvc接口请求参数
    ThreadLocal 结构
    遇到的问题
    jsonview的安装
    Java
    学习资源
    Java
    Java
    Java
    Java
  • 原文地址:https://www.cnblogs.com/Bella2017/p/11392763.html
Copyright © 2011-2022 走看看