Thursday, March 12, 2015

85. Maximal Rectangle Leetcode Java

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
Solution:
This problem can be divided to N of problem 84. Largest rectangle in histogram 
We can divided this problem row by row and treat the problem as the last problem with the base from row 1 to n. And the maximum rectangle must be the largest among them. 
We need a int array to store the height for each row, the good thing is that we don't need to recalculate the height every time, each time if it is a 0 in that column, the height will be 0, and if it is 1, the height of that column increment by 1. Once we have the height for that row, we can call the method of last problem to calculate the largest rectangle with that row as the base. Update the final result as needed.
Time Complexity: O(m*n) 
 public int maximalRectangle(char[][] matrix) {  
    if(matrix==null || matrix.length==0 || matrix[0].length==0) return 0;  
    int res=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++){  
        if(matrix[i][j]=='0') height[j]=0;  
        else height[j]++;  
      }  
      res=Math.max(res,helper(height));  
    }  
    return res;  
   }  
   public int helper(int[] height){  
     int res=0;  
     Stack<Integer> st=new Stack<Integer>();  
     for(int i=0;i<height.length;i++){  
       while(!st.isEmpty() && height[i]<height[st.peek()]){  
         int h=height[st.pop()];  
         int w=(st.isEmpty())? i : i-st.peek()-1;  
         res=Math.max(res,h*w);  
       }  
       st.push(i);  
     }  
     while(!st.isEmpty()){  
       int h=height[st.pop()];  
       int w=(st.isEmpty())? height.length:height.length-st.peek()-1;  
       res=Math.max(res,h*w);  
     }  
     return res;  
   }  

No comments:

Post a Comment