LeetCode:Maximal Rectangle

来源:互联网 发布:万能的淘宝 编辑:程序博客网 时间:2024/05/16 06:18

Maximal Rectangle




Total Accepted: 43628 Total Submissions: 183613 Difficulty: Hard

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

Subscribe to see which companies asked this question

Hide Tags
 Array Hash Table Stack Dynamic Programming
Hide Similar Problems
 (H) Largest Rectangle in Histogram (M) Maximal Square













思路:

解法类似于【Largest Rectangle in Histogram】。


java code:

public class Solution {    public int maximalRectangle(char[][] matrix) {                if(matrix==null || matrix.length==0) return 0;        int m = matrix.length;        int n = matrix[0].length;                int[] height = new int[n+1];        int maxArea = 0;                for(int row = 0;row < m;row++) {            Stack<Integer> stack = new Stack<>();                        for(int col = 0; col <= n; col++) {                                if(col < n) {                    if(matrix[row][col] == '1') height[col]++;                    else height[col] = 0;                }                                if(stack.isEmpty() || height[col] >= height[stack.peek()])                    stack.push(col);                else {                    while(!stack.isEmpty() && height[col] < height[stack.peek()]) {                        int tmp = stack.pop();                        int wid = stack.isEmpty() ? col : col - stack.peek() - 1;                        maxArea = Math.max(maxArea, height[tmp] * wid);                    }                    stack.push(col);                }            }        }        return maxArea;    }}


0 0
原创粉丝点击