85. Maximal Rectangle


July-27-2019

84. Largest Rectangle in Histogram的延伸版。。以每一行建图,然后用84的方程算。
按理说这个应该是221. Maximal Square的变体,221是看左、上、左上的DP来算,因为221里面是算正方形,这里是矩形,直接没法确定了。

class Solution {
    public int maximalRectangle(char[][] matrix) {
        if (matrix.length == 0 || matrix[0].length == 0) return 0;
        int[] graph = new int[matrix[0].length + 1];
        graph[graph.length - 1] = 0;
        int res = 0;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (matrix[i][j] == '0') {
                    graph[j] = 0;
                } else {
                    graph[j] += 1;
                }
            }
            res = Math.max(res, getArea(graph));
        }
        return res;
    }
    
    
    private int getArea(int[] nums) {
        int res = 0;
        ArrayDeque stk = new ArrayDeque<>();
        for (int i = 0; i < nums.length; i++) {
            if (stk.isEmpty() || nums[stk.peek()] < nums[i]) {
                stk.push(i);
            } else {
                int height = nums[stk.pop()];
                int len = 0;
                if (stk.isEmpty()) {
                    len = i;
                } else {
                    len = i - stk.peek() - 1;
                }
                System.out.println(height + " " + len);
                res = Math.max(res, height * len);
                i --;
            }
        }
        return res;
    }
}

转载于:https://www.cnblogs.com/reboot329/p/11259232.html

你可能感兴趣的:(85. Maximal Rectangle)