美文网首页
85. 最大矩形

85. 最大矩形

作者: justonemoretry | 来源:发表于2021-08-20 22:34 被阅读0次
image.png
image.png

解法

class Solution {
    public int maximalRectangle(char[][] matrix) {
        int row = matrix.length;
        if (row == 0) {
            return 0;
        }
        int col = matrix[0].length;
        // 统计每一个点左侧连续1的长度
        int[][] left = new int[row][col];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (matrix[i][j] == '1') {
                    left[i][j] = j == 0 ? 1 : left[i][j - 1] + 1;
                }
            }
        }

        int maxArea = 0;
        Stack<Integer> stack = new Stack<>();
        for (int j = 0; j < col; j++) {
            // 逐列转化为求矩阵最大面积的题
            // 求出列中每个点每一个上面和下面第一个小于节点的位置
            int[] up = new int[row];
            for (int i = 0; i < row; i++) {
                while (!stack.isEmpty() && left[stack.peek()][j] >= left[i][j]) {
                    stack.pop();
                }
                up[i] = stack.isEmpty() ? -1 : stack.peek();
                stack.push(i);
            }
            stack.clear();

            int[] down = new int[row];
            for (int i = row - 1; i >= 0; i--) {
                while (!stack.isEmpty() && left[stack.peek()][j] >= left[i][j]) {
                    stack.pop();
                }
                down[i] = stack.isEmpty() ? row : stack.peek();
                stack.push(i);
            }
            stack.clear();

            for (int i = 0; i < row; i++) { 
                int height = down[i] - up[i] - 1;
                maxArea = Math.max(maxArea, height * left[i][j]);
            }
        }
        return maxArea;
    }
}

相关文章

网友评论

      本文标题:85. 最大矩形

      本文链接:https://www.haomeiwen.com/subject/exrxiltx.html