85. 最大矩形

85. 最大矩形

难度:困难

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

示例 1:

img

输入: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
  • 0 <= row, cols <= 200
  • matrix[i][j]'0''1'

解答:

class Solution {
    //单调栈
    //时间复杂度O(MN), 空间复杂度O(MN)
    public int maximalRectangle(char[][] matrix) {
        if(matrix.length == 0) return 0;
        int[] heights = new int[matrix[0].length];
        int maxAns = 0;
        for(int i = 0; i < matrix.length; i++){
            for(int j = 0; j < matrix[0].length; j++){
                if(matrix[i][j] == '1') heights[j] += 1;
                else heights[j] = 0;
            }
            maxAns = Math.max(maxAns, largestRectangleArea(heights));
        }
        return maxAns;
    }
    
    public int largestRectangleArea(int[] heights){
        int[] stack = new int[heights.length + 1];
        int topIndex = 0;
        int maxAns = 0;
        stack[topIndex++] = -1;
        for(int i = 1; i < heights.length; i++){
            while(topIndex > 0 && heights[stack[topIndex]] > heights[i]){
                maxAns = Math.max(maxAns, heights[stack[topIndex]] * (i - stack[topIndex - 1] - 1));
                topIndex--;
            }
            stack[++topIndex] = i;
        }
        while(topIndex > 0){
            maxAns = Math.max(maxAns, heights[stack[topIndex]] * (heights.length - stack[topIndex - 1] - 1));
            topIndex--;
        }
        return maxAns;
    }
}

参考自:

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/maximal-rectangle/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-1-8/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Finish_Hou

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值