Tuesday, December 30, 2014

Maximal Rectangle (LeetCode Array)

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

Idea: I made use of the "maximum area size in histogram". For each block in the matrix, calculate its height (consecutive 1's above it). The apply "maximum area size in histogram" on each row and update the maximal rectangle size.

Time: O(n^2) Space: O(n^2)

Code:
 public class Solution {  
   public int maximalRectangle(char[][] matrix) {  
     if(matrix.length==0||matrix[0].length==0)  
       return 0;  
     int[][] height=new int[matrix.length][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[i][j]=0;  
         }  
         else  
         {  
           height[i][j]=(i==0)?1:height[i-1][j]+1;  
         }  
       }  
     }  
     int result=0;  
     for(int i=0;i<matrix.length;i++)  
       result=Math.max(result,maxAreaHist(height[i]));  
     return result;  
   }  
   public int maxAreaHist(int[] height)  
   {  
     if(height==null||height.length==0)  
       return 0;  
     Stack<Integer> indexStack=new Stack<Integer>();  
     int maxArea=0;  
     for(int i=0;i<=height.length;i++)  
     {  
       int current=(i==height.length)?-1:height[i];  
       while(!indexStack.isEmpty()&&height[indexStack.peek()]>=current)  
       {  
         int h=height[indexStack.pop()];  
         int w=indexStack.isEmpty()?i:i-1-indexStack.peek();  
         maxArea=Math.max(maxArea,h*w);  
       }  
       indexStack.push(i);  
     }  
     return maxArea;  
   }  
 }  

No comments:

Post a Comment