Leetcode. 2866.美丽塔II

Leetcode. 2866.美丽塔II_第1张图片

要求O(N)复杂度内解决,考虑单调栈,这个题很像经典的美丽度的那个单调栈的模板题

对有每一个位置,考虑右边能扩展到哪来?不如直接从末尾来倒着看,发现从末尾需要维护一个单调增的单调栈,单调栈里面存下标就好了很经典

同理左边能扩展到哪里?也是直接 从开头直接开始看就行了

这个题目唯一需要注意的一点就是我们一开始处理边界的时候可以放一个n(算右边能扩展的时候)同理算左边的时候你直接放一个-1 注意不要RE访问-1就好了

算是很板的一道题目

using ll = long long;
class Solution {
public:
    long long maximumSumOfHeights(vector& maxHeights) {
        int n = maxHeights.size();
        vectorleft(n+10,0);
        vectorright(n+10,0);
        stackstk;
        stk.push(n);
        for(int i=n-1;i>=0;i--){
            ll tem = maxHeights[i];
            while(stk.size()>1&&tem<=maxHeights[stk.top()])stk.pop();
            right[i] = right[stk.top()];
            right[i]+=(stk.top()-i)*tem;

            stk.push(i);
        }



        while(stk.size())stk.pop();
        stk.push(-1);
        for(int i=0;i1&&tem<=maxHeights[stk.top()])stk.pop();
            
            if(stk.size()>1) left[i] = left[stk.top()];
            else left[i] =0; 
            left[i]+=(i-stk.top())*tem;

            stk.push(i);
        }

        ll ans = 0;
        for(int i=0;i

你可能感兴趣的:(单调栈,leetcode,算法)