85. 最大矩形

给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

示例:

输入:
[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]
输出: 6

class Solution {
    public int maximalRectangle(char[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
        int m = matrix.length;
        int n = matrix[0].length;
        int res = 0;
        int[] dp = new int[matrix[0].length];
        for(int i = 0;i < m;i++){
            for(int j = 0;j < n;j++){
                dp[j] = matrix[i][j] == '1' ? dp[j] + 1 : 0;
            }
            res = Math.max(res,getL(dp));
        }
        return res;
    }
    private int getL(int[] nums){
        //单调增栈
        Stack<Integer> stack = new Stack<>();
        stack.push(-1);
        int res = 0;
        for(int i = 0;i < nums.length;i++){
            while(stack.peek() != -1 && nums[stack.peek()] >= nums[i]){
                res = Math.max(res,nums[stack.pop()] * (i - stack.peek() - 1));
            }
            stack.push(i);
        }
        while(stack.peek() != -1){
            res = Math.max(res, nums[stack.pop()] * (nums.length - stack.peek() - 1));
        }
        return res;
    }
}

 

posted @ 2020-04-11 19:55  海绵爱上星  阅读(110)  评论(0编辑  收藏  举报