最大子矩阵

import java.util.*;

public class Solution {
    public int maximalRectangle(char[][] matrix) {
        if(matrix.length==0 || matrix[0].length==0 || matrix==null) return 0;
        int[] height = new int[matrix[0].length];  //与列数有关
        int res = 0;
        for(int i=0;i<matrix.length;i++){
            for(int j=0;j<matrix[0].length;j++){
                height[j] = matrix[i][j]=='0'? 0 : height[j]+1;  //只能统计连续的1,若不连续则一定清零
            }
            res = helper(height,res);
        }
        return res;
    }

    public int helper(int[] height , int res){
        Stack<Integer> st = new Stack<Integer>();
        for(int i=0;i<height.length;i++){
            while(!st.empty() && height[st.peek()]>=height[i]){    //找到满足条件的i的插入位置
                int top = st.pop(); //当前的栈顶
                int left = st.empty()?-1:st.peek();
                res = Math.max(res, height[top]*(i-left-1));
            }  //找寻i的恰当插入位置,并且及时更新当前的最优解
            st.push(i);
        }
        while(!st.empty()){   //剩余部分的左边界即为st.top(),右边界是n-1
            int top = st.pop();
            int left = st.empty()?-1:st.peek();
            res = Math.max(res,height[top]*(height.length-1-left));
        }
        return res;
    }
    
    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值