leetcode 85. 最大矩形

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

 

示例 1:


输入: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'

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximal-rectangle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

按照每一行单调栈的思路,来解答。leetcode 84. 柱状图中最大的矩形

    private Stack<Integer> index = new Stack<>();
    private Stack<Integer> value = new Stack<>();
    public int maximalRectangle(char[][] matrix) {
        if (matrix.length == 0) {
            return 0;
        }
        int b = matrix[0].length;
        if (b == 0) {
            return 0;
        }
        int m = 0;
        index.add(-1);
        value.add(0);

        int[] arr = new int[b];
        for (char[] chars : matrix) {
            for (int i = 0; i < b; i++) {
                if (chars[i] == '0') {
                    arr[i] = 0;
                } else {
                    arr[i] += 1;
                }
            }
            m = Math.max(m, largestRectangleArea(arr));
        }
        return m;
    }

    private int largestRectangleArea(int[] heights) {
        if (heights == null || heights.length == 0) {
            return 0;
        }
        int length = heights.length;
        int max = 0;
        for (int i = 0; i < length; i++) {
            int v = heights[i];
            if (value.peek() > v) {
                Integer st = index.peek();
                while (value.peek() > v) {
                    int item = value.pop();
                    index.pop();
                    int l = st - index.peek();
                    max = Math.max(max, l * item);
                }
            }
            value.add(v);
            index.add(i);
        }
        if (!value.isEmpty()) {
            Integer st = index.peek();
            while (value.size() > 1) {
                int item = value.pop();
                index.pop();
                int l = st - index.peek();
                max = Math.max(max, l * item);
            }
        }
        return max;
    }

posted @ 2021-06-16 20:41  旺仔古李  阅读(59)  评论(0编辑  收藏  举报