2866.美丽塔 II

​​题目来源:

        leetcode题目,网址:2866. 美丽塔 II - 力扣(LeetCode)

解题思路:

       单调栈+dp。维护两个数组 pre 和 suffix,pre[i] 表示以第 i 个为山峰时 [0,i] 的最大值,suffix[i]表示以 第 i 个为山峰时 [i,n-1] 的最大值。pre[i]+suffix[i]-maxHeights[i] 的最大值即为所求。 

解题代码:

class Solution {
public:
    long long maximumSumOfHeights(vector<int>& maxHeights) {
        vector<long long> pre=getPreVector(maxHeights);
        vector<long long> suffix=getSuffixVector(maxHeights);
        long long res=0;
        for(int i=0;i<maxHeights.size();i++){
            res=max(pre[i]+suffix[i]-maxHeights[i],res);
        }
        return res;

    }
    vector<long long> getSuffixVector(vector<int>& maxHeights){
        int n=maxHeights.size();
        vector<long long> res(n);
        stack<int> stack1;
        for(int i=n-1;i>=0;i--){
            while(!stack1.empty()&& maxHeights[i]<maxHeights[stack1.top()]){
                stack1.pop();
            }
            if(stack1.empty()){
                res[i]=(long long)(n-i)*(maxHeights[i]);
            }else{
                int j=stack1.top();
                res[i]=(long long)(j-i)*maxHeights[i]+res[j];
            }
            stack1.push(i);
        }
        return res;
    
    }
    vector<long long> getPreVector(vector<int>& maxHeights){
        vector<long long> res;
        stack<int> stack1;
        for(int i=0;i<maxHeights.size();i++){
            while(!stack1.empty() && maxHeights[i]<maxHeights[stack1.top()]){
                stack1.pop();
            }
            if(stack1.empty()){
                res.push_back((i+1)*(long long)maxHeights[i]);
            }else{
                int j=stack1.top();
                res.push_back((i-j)*(long long)maxHeights[i]+res[j]);
            }
            stack1.push(i);
        }
        return res;
    }
};
 

总结:

        没想出来,看官方题解的。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值