Saturday, February 28, 2015

LeetCode Max Rectangle Area

Same idea of Max area in a histgram.

But we need a array to store the height of each row. We dont need calculate the height every time.
Just check the current character and the previous height. we can get the height array.

Here is the code.
public int maximalRectangle(char[][] matrix) {
        if (matrix==null || matrix.length==0 || matrix[0].length==0) return 0;
        int maxArea = 0;
        int[] height = new int[matrix[0].length];
        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;
            }
            maxArea = Math.max(maxArea, calMaxArea(height));
        }
        return maxArea;
    }
   
    private int calMaxArea(int[] height) {
        Stack<Integer> stack = new Stack<Integer>();
        int maxArea = 0;
        int i=0;
        int[] h = new int[height.length+1];
        h = Arrays.copyOf(height, height.length+1);
        while (i<h.length) {
            if (stack.isEmpty() || h[stack.peek()]<=h[i]) {
                stack.push(i++);
            } else {
                int t = stack.pop();
                maxArea = Math.max(maxArea, h[t] * (stack.isEmpty() ? i : i-stack.peek()-1));
            }
        }
       
        return maxArea;
    }

No comments:

Post a Comment