85. 最大矩形(LeetCode)(单调栈思想)

85. 最大矩形

单调栈思想,在基准线上寻找往上连续的1的最大值

class Solution {
public:
    int maxv(vector<int>& heights){
        int n = heights.size();
        vector<int> left(n), right(n);
        stack<int> stk;

        for(int i = 0; i < n; ++i){
            while(stk.size() && heights[stk.top()] >= heights[i]) stk.pop();
            if(stk.empty()) left[i] = -1;
            else left[i] = stk.top();
            stk.push(i);
        }
        stk = stack<int>();
        for(int i = n - 1; i >= 0; --i){
            while(stk.size() && heights[stk.top()] >= heights[i]) stk.pop();
            if(stk.empty()) right[i] = n;
            else right[i] = stk.top();
            stk.push(i);
        }
        int maxv = 0;
        for(int i = 0; i < n; ++i) maxv = max(maxv, (right[i] - left[i] - 1) * heights[i]);
        return maxv;
    }
    

    int maximalRectangle(vector<vector<char>>& matrix) {
        int row = matrix.size(), col = matrix[0].size();
        vector<vector<int>>  h(row, vector<int>(col));

        for(int i = 0; i < row; ++i){
            for(int j = 0; j < col; ++j){
                if(matrix[i][j] == '1'){
                    if(i) h[i][j] = h[i-1][j] + 1;
                    else h[i][j] = 1;
                }
            }
        }

        int res = 0;
        for(int i = 0; i < row; ++i) res = max(res, maxv(h[i]));

        return res;
    }
};
posted @ 2025-03-11 18:25  awei040519  阅读(9)  评论(0)    收藏  举报