leetcode 85. Maximal Rectangle(最大矩形)

本文介绍了一种解决二维矩阵中由字符'1'构成的最大矩形面积问题的方法。通过将每行转换为直方图并应用84题的直方图最大矩形面积算法,实现了高效求解。详细阐述了算法思路及其实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.

Example:

Input:
[
[“1”,“0”,“1”,“0”,“0”],
[“1”,“0”,“1”,“1”,“1”],
[“1”,“1”,“1”,“1”,“1”],
[“1”,“0”,“0”,“1”,“0”]
]
Output: 6

给出一个二维的char数组,判断其中‘1’构成的最大矩形面积

注意两点:1,input是char类型数组,而不是int , 2.矩形

思路:
两种方法,一种是84题的拓展,一种是dp

(1) 84题的拓展
一层一层读input,把每个元素看成直方图的高度,用一个数组heights[]保存累加高度
第一行: heights={1, 0, 1, 0, 0}
第二行:heights变成{2, 0, 2, 1, 1}

即元素=0时,heights对应的元素清0, =1时heights对应元素+1

把heights看作是一个直方图,这时转化为求直方图中最大矩形面积
每一行设置完heights后,都求一次最大矩形面积

其中maxHistArea函数为求直方图最大矩阵面积函数,参照84题代码

    public int maximalRectangle(char[][] matrix) {
        if(matrix == null || matrix.length == 0) {
            return 0;
        }
        
        int m = matrix.length;
        int n = matrix[0].length;
        
        int[] height = new int[n];
        int result = 0;
        
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(matrix[i][j] - '0' == 0) {
                    height[j] = 0;
                } else {
                    height[j] ++;
                }
            }
            result = Math.max(result, maxHistArea(height));
        }
        return result;
    }
    
    public int maxHistArea(int[] hist) {
        if(hist == null || hist.length == 0) {
            return 0;
        }
        
        Stack<Integer> st = new Stack<>();
        int area = 0;
        int n = hist.length;
        
        for(int i = 0; i < n; i++) {
            while(!st.isEmpty() && hist[st.peek()] > hist[i]) {
                int cur = st.pop();
                area = Math.max(area, hist[cur] * (st.isEmpty() ?
                                                  i:i-st.peek()-1));
            }
            st.push(i);
        }
        
        while(!st.isEmpty()) {
            int cur = st.pop();
            area = Math.max(area, hist[cur] * (st.isEmpty() ?
                                                  n:n-st.peek()-1));
        }
        
        return area;
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

蓝羽飞鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值