85. 最大矩形 (Hard)

发布时间 2023-06-13 15:36:30作者: zwyyy456

问题描述

85. 最大矩形 (Hard) 给定一个仅包含 01 、大小为 rows x cols 的二维二进 制矩阵,找出只包含 1 的最大矩形,并返回其面积。

示例 1:

![](https://assets.leetcode.com/uploads/2020/09/14/maximal.j pg)

输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],
["1","1","1","1","1"],["1","0","0","1","0"]]
输出:6
解释:最大矩形如上图所示。

示例 2:

输入:matrix = []
输出:0

示例 3:

输入:matrix = [["0"]]
输出:0

示例 4:

输入:matrix = [["1"]]
输出:1

示例 5:

输入:matrix = [["0","0"]]
输出:0

提示:

  • rows == matrix.length
  • cols == matrix[0].length
  • 1 <= row, cols <= 200
  • matrix[i][j]'0''1'

解题思路

其实本题就相当于是 84. 柱状图中最大的矩形 (Hard) 套了一层皮,想到了这一点之后就不难了。

代码

class Solution {
  public:
    int Count(int row, int n, vector<int> &vec, vector<vector<char>> &matrix) {
        for (int i = 0; i < n; ++i) {
            vec[i] = matrix[row][i] == '0' ? 0 : vec[i] + 1;
        }
        // 单调递增栈
        stack<int> stk;
        int res = 0;
        for (int i = 0; i < n; ++i) {
            while (!stk.empty() && vec[i] < vec[stk.top()]) {
                int idx = stk.top(), h = vec[idx];
                stk.pop();
                int rec = stk.empty() ? h * i : h * (i - stk.top() - 1);
                res = max(rec, res);
            }
            stk.push(i);
        }
        while (!stk.empty()) {
            int idx = stk.top();
            int h = vec[idx];
            stk.pop();
            int rec = stk.empty() ? h * n : h * (n - stk.top() - 1);
            res = max(res, rec);
        }
        return res;
    }
    int maximalRectangle(vector<vector<char>> &matrix) {
        // 二维前缀和?
        // 转化为 84 题,即可用单调栈解决
        int m = matrix.size(), n = matrix[0].size();
        int res = 0;
        vector<int> vec(n);
        for (int i = 0; i < m; ++i) {
            res = max(res, Count(i, n, vec, matrix));
        }
        return res;
    }
};