Leetcode 85. Maximal Rectangle

/**
 * Scan row by row.
 * Calculate the histogram for each row. e.g. for row 2 the histogram is 2, 0, 2, 1, 1
 * Calculate the largest area of this histogram. 
 */ 
public class Solution {
    public int maximalRectangle(char[][] matrix) {
        if (matrix==null || matrix.length==0) {
            return 0;
        }
        
        int max = 0;
        int row = matrix.length;
        int col = matrix[0].length;
        int[][] height = new int[row][col];
        
        // calculate the histogram for each row
        for (int i=0; i<row; i++) {
            for (int j=0; j<col; j++) {
                if (matrix[i][j] == '1') {
                    height[i][j] = (i==0) ? 1 : height[i-1][j]+1;
                }
            }
        }
        
        // calculate the largest area of each histogram
        for (int i=0; i<row; i++) {
            int currMax = 0;
            Stack<Integer> stack = new Stack<>();
            for (int j=0; j<=col; j++) {
                int curr = (j==col) ? 0 : height[i][j];
                while (!stack.isEmpty() && curr < height[i][stack.peek()]) {
                    int h = height[i][stack.pop()];
                    int w = stack.isEmpty() ? j : j - stack.peek() - 1;
                    currMax = Math.max(currMax, h*w);
                }
                stack.push(j);
            }
            max = Math.max(max, currMax);
        }
        
        return max;
    }
}

發佈了187 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章