跳转至

最大矩形⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

class Solution {
private:
    int largestRectangleArea(vector<int>& height) {
        int n = height.size();
        int res = 0;
        stack<int> stk;

        for (int i = 0; i < n; i++) {
            while (!stk.empty() && height[stk.top()] >= height[i]) {
                int current = stk.top();
                stk.pop();
                int left = !stk.empty() ? stk.top() : -1;
                res = max(res, height[current] * (i - left - 1));
            }
            stk.push(i);
        }

        while (!stk.empty()) {
            int current = stk.top();
            stk.pop();
            int left = !stk.empty() ? stk.top() : -1;
            res = max(res, height[current] * (n - left - 1));
        }

        return res;
    }

public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        int n = matrix.size(), m = matrix[0].size();
        vector<int> height(m, 0);
        int res = 0;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                height[j] = matrix[i][j] == '0' ? 0 : height[j] + 1;
            }
            res = max(largestRectangleArea(height), res);
        }

        return res;
    }
};