单调栈 基于Leetcode 084 柱状图中最大的矩形思想-----Leetcode 085最大矩形

Leetcode 084题解地址

https://blog.csdn.net/qq_52934831/article/details/121753758

地址

https://leetcode-cn.com/problems/maximal-rectangle/submissions/

描述

在这里插入图片描述

思想

在这里插入图片描述

代码

class Solution {
    
    
public:
    //借助84题求柱状图中最大的矩形
    int largestRectangleArea(vector<int>& h) {
    
    
        int n=h.size();
        stack<int>s;//存放下标
        //left[i]存放i左边比h[i]小的柱子的最近下标。
        //right[i]存放i右边比h[i]小的柱子的最近下标。
        vector<int> left(n),right(n);
        //计算left
        for(int i=0;i<n;i++){
    
    
            while(!s.empty()&&h[i]<=h[s.top()]) s.pop();
            if(s.empty()) left[i]=-1;
            else left[i]=s.top();
            s.push(i);
        }
        //清空栈
        s=stack<int>();
        //计算right
        for(int i=n-1;i>=0;i--){
    
    
            while(!s.empty()&&h[i]<=h[s.top()]) s.pop();
            //!!!!注意!!!!
            //右边和左边不一样
            if(s.empty()) right[i]=n;
            else right[i]=s.top();
            s.push(i);
        }
        //计算最大面积
        int res=0;
        for(int i=0;i<n;i++){
    
    
            res=max(res,h[i]*(right[i]-left[i]-1));
        }
        return res;
    }
    int maximalRectangle(vector<vector<char>>& matrix) {
    
    
        int n=matrix.size(),m=matrix[0].size();
        //枚举h[i][j]这列上有多少1
        vector<vector<int>> h(n,vector<int>(m));
        for(int i=0;i<n;i++){
    
    
            for(int j=0;j<m;j++){
    
    
                if(matrix[i][j]=='1'){
    
    
                    if(i) h[i][j]=1+h[i-1][j];
                    else h[i][j]=1;
                }

            }
        }
        int res=0;
        for(int i=0;i<n;i++) res=max(res,largestRectangleArea(h[i]));
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_52934831/article/details/121755627