Max  rectangle | Practice | GeeksforGeeks

Given a binary matrix M of size n X m. Find the maximum area of a rectangle formed only of 1s in the given matrix. 
Example 1:
Input:
n = 4, m = 4
M[][] = {{0 1 1 0},
         {1 1 1 1},
         {1 1 1 1},
         {1 1 0 0}}
Output: 8
Explanation: For the above test case the
matrix will look like
0 1 1 0
1 1 1 1
1 1 1 1
1 1 0 0
the max size rectangle is 
1 1 1 1
1 1 1 1
and area is 4 *2 = 8.
Your Task: 
Your task is to complete the function maxArea which returns the maximum size rectangle area in a binary-sub-matrix with all 1’s. The function takes 3 arguments the first argument is the Matrix M[ ] [ ] and the next two are two integers n and m which denotes the size of the matrix M. 
Expected Time Complexity : O(n*m)
Expected Auixiliary Space : O(m)
Constraints:
1<=n,m<=1000
0<=M[][]<=1

Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.
+1
anilcangulkaya73 days ago
0.89/2.62


#define xSafe(x, n) (x < n)
#define ySafe(y, m) (y < m)

int maxArea(int M[MAX][MAX], int n, int m) {
    // Your code here
    int maxCount = 0;
    for(int x = 0; x < n; ++x)
    for(int y = 0; y < m; ++y)
        for(int i = 0; M[x + i][y] && xSafe(i + x, n); ++i)
        {
            for(int j = 0; ySafe(j + y, m); ++j)
            {
                for(int k = 0; k <= i; ++k)
                if(!M[x+k][y+j]) { goto not_correct; }
            
                maxCount = max((i + 1) * (j + 1), maxCount);
            }
            not_correct:{}
        }
        
    return maxCount;
}
0
bobbyprajapati962 weeks ago
Simple Java Solution
class Solution {    static int[] prevSmaller(int arr[]){       Stack<Integer> st = new Stack<>();       int ans[] = new int[arr.length];       ans[0] = -1;       for(int i=0;i<arr.length;i++)       {           while(!st.isEmpty() && arr[st.peek()]>=arr[i])           st.pop();              ans[i]=st.isEmpty()?-1:st.peek();       st.push(i);       }       return ans;   }      static int[] nextSmaller(int arr[]){       Stack<Integer> st = new Stack<>();       int ans[] = new int[arr.length];       ans[arr.length-1] = arr.length;       st.push(arr.length-1);       for(int i=arr.length-1;i>=0;i--){           while(!st.isEmpty() && arr[st.peek()]>=arr[i]) st.pop();           ans[i] = st.isEmpty()?arr.length:st.peek();           st.push(i);       }       return ans;   }      //Function to find largest rectangular area possible in a given histogram.   public static int getMaxArea(int hist[], int n) {       // your code here       int prev[] = prevSmaller(hist);       int next[] = nextSmaller(hist);       int max = 0;       for(int i=0;i<n;i++)       max = Math.max(max,(next[i]-prev[i]-1)*hist[i]);       return max;   }          public int maxArea(int a[][], int n, int m) {       // add code here.       int currRow[]=a[0];       int x=currRow.length;       int maxAns=getMaxArea(currRow,x);       for(int i=1;i<a.length;i++)       {           for(int j=0;j<a[0].length;j++)           {               if(a[i][j]==1)                  currRow[j]+=1;               else                  currRow[j]=0;           }           int currAns=getMaxArea(currRow,x);           maxAns=Math.max(maxAns,currAns);       }       return maxAns;          }}
+1
aloksinghbais023 weeks ago
C++ solution having time complexity as O(n*m) and space complexity as O(m) is as follows :- 
 
Execution Time :- 1.62 / 2.69 sec
 
int maxArea(int M[MAX][MAX], int n, int m) {       int his[m];              int ans = 0;       for(int i = 0; i<n; i++){           if(i == 0){               for(int j = 0; j < m; j++) his[j] = M[i][j];           }           else{               for(int j = 0; j < m; j++){                   if(M[i][j] == 0) his[j] = 0;                   else his[j] += M[i][j];               }           }                      stack<int> stk;           vector<int> nser(m);           for(int j = m-1; j>=0; j--){               while(!stk.empty() && his[stk.top()] >= his[j]) stk.pop();               if(!stk.empty()) nser[j] = stk.top();               else nser[j] = m;               stk.push(j);           }                      while(!stk.empty()) stk.pop();           vector<int> nsel(m);           for(int j = 0; j<m; j++){               while(!stk.empty() && his[stk.top()] >= his[j]) stk.pop();               if(!stk.empty()) nsel[j] = stk.top();               else nsel[j] = -1;               stk.push(j);           }                      int mx = 0;           for(int j = 0; j < m; j++){               int li = nsel[j] + 1;               int ri = nser[j] - 1;               mx = max(mx,(ri-li+1)*his[j]);           }                      ans = max(ans,mx);                  }       return (ans);   }
0
himanshukug19cs4 weeks ago
java solution
 public int maxArea(int mat[][], int n, int m) {       // add code here.       int ans=0;       int[] h = new int[m];       for(int i=0;i<n;i++){           for(int j=0;j<m;j++){               if(mat[i][j]==0)                   h[j]=0;               else if(mat[i][j]==1)                  h[j]+=1;           }        ans=Math.max(ans,getMaxArea(h,m));       }        return ans;          }     int getMaxArea(int heights[], int n1)    {       int n=heights.length;       int maxArea=-1;              int[] nsl=nslIndex(heights,n);       int[] nsr=nsrIndex(heights,n);              for(int i=0;i<n;i++){           int width=nsr[i]-nsl[i]-1;           int area=heights[i]*width;           maxArea=Math.max(maxArea,area);       }       return maxArea;   }     int[] nslIndex(int[] arr, int n){              Stack<Integer> s=new Stack<>();       int[] l=new int[n];              for(int i=0;i<n;i++){           while(!s.isEmpty() && arr[i]<=arr[s.peek()])               s.pop();           if(s.isEmpty())               l[i]=-1;           else               l[i]=s.peek();           s.add(i);       }       return l;   }    static int[] nsrIndex(int[] arr, int n){          Stack<Integer> s=new Stack<>();       int[] l=new int[n];              for(int i=n-1;i>=0;i--){           while(!s.isEmpty() && arr[i]<=arr[s.peek()])               s.pop();           if(s.isEmpty())               l[i]=n;           else               l[i]=s.peek();           s.add(i);       }       return l;   }         
+1
swastikp17111 month ago
Standard Java Solution using Maximum Rectangular Area in a Histogram
 
class Histogram
{
    public static int[] nslIndex(int[] arr, int n){
    
        Stack<Integer> s=new Stack<>();
        int[] l=new int[n];
        
        for(int i=0;i<n;i++){
            while(!s.isEmpty() && arr[i]<=arr[s.peek()])
                s.pop();
            if(s.isEmpty())
                l[i]=-1;
            else
                l[i]=s.peek();
            s.add(i);
        }
        return l;
    }
    public static int[] nsrIndex(int[] arr, int n){
    
        Stack<Integer> s=new Stack<>();
        int[] l=new int[n];
        
        for(int i=n-1;i>=0;i--){
            while(!s.isEmpty() && arr[i]<=arr[s.peek()])
                s.pop();
            if(s.isEmpty())
                l[i]=n;
            else
                l[i]=s.peek();
            s.add(i);
        }
        return l;
    }
    public static int getMaxArea(int heights[], int n) 
    {
        int maxArea=-1;
        
        int[] nsl=nslIndex(heights,n);
        int[] nsr=nsrIndex(heights,n);
        
        for(int i=0;i<n;i++){
            int width=nsr[i]-nsl[i]-1;
            int area=heights[i]*width;
            maxArea=Math.max(maxArea,area);
        }
        return maxArea;
    }
        
}
class Solution {
    public int maxArea(int M[][], int n, int m) {
    
        int[] heights=new int[m];
        Histogram h=new Histogram();
        
        int maxArea=-1;
        
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                heights[j]= M[i][j]==0 ? heights[j]=0 : heights[j]+M[i][j];
            }
            int area=h.getMaxArea(heights,m);
            maxArea=Math.max(maxArea,area);
        }
        return maxArea;
    }
}
0
santoshkumarroy971 month ago
// { Driver Code Startsimport java.util.*;
class FindMinCost{public static void main(String args[]){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t > 0) {  int n = sc.nextInt();  int m = sc.nextInt();  int arr[][] = new int[n][m];  for(int i=0; i<n; i++)  {   for(int j=0; j<m; j++ )   {    arr[i][j] = sc.nextInt();   }  }  System.out.println(new Solution().maxArea(arr, n, m)); t--; }}}// } Driver Code Ends
/*Complete the function given below*/class Solution {   public int maxArea(int M[][], int n, int m) {       // add code here.       int ans=0;       int col=M[0].length;       int arr[]=new int[col]; // main arr;                     for(int i=0;i<M.length;i++){           int ptr=0;           for(int j=0;j<col;j++){               if(M[i][j]==1){               arr[ptr]+=1;               }                              else{               arr[ptr]=0;               }                              ptr++;           }                      Stack<Integer> s=new Stack<>();                      int left[]=new int[arr.length];           int right[]=new int[arr.length];                      for(int a=0;a<arr.length;a++){/////////                              while(!s.isEmpty() && arr[s.peek()]>=arr[a]){                   s.pop();               }               if(s.isEmpty()){               left[a]=-1;               }               else{               left[a]=s.peek();               }                                             s.push(a);                          }//////////                      s.clear();                      for(int a=arr.length-1;a>=0;a--){/////////                              while(!s.isEmpty() && arr[s.peek()]>=arr[a]){                   s.pop();               }               if(s.isEmpty())               right[a]=arr.length;               else               right[a]=s.peek();                                             s.push(a);                          }//////////           for(int a=0;a<arr.length;a++){           int area=(right[a]-left[a]-1)*arr[a];           ans=Math.max(area,ans);           }                      s.clear();       }       return ans;   }}
0
santoshkumarroy97
This comment was deleted.
0
hanumanmanyam8371 month ago
class Solution {
    public static int getMaxArea(int arr[], int n) 
    {
        // your code here
        Stack<Integer>st=new Stack<>();
        int res=0;
        for(int i=0;i<n;i++)
        {
            while(!st.isEmpty() && arr[st.peek()]>=arr[i])
            {
                int t=st.pop();
                int area=arr[t]*(st.isEmpty()?i:i-st.peek()-1);
                res=Math.max(res,area);
                
            }
            st.push(i);
        }
        while(!st.isEmpty())
        {
            
                int a=st.pop();
                int are=arr[a]*(st.isEmpty()?n:n-st.peek()-1);
                res=Math.max(res,are);
                
            
        }
        return res;
    }
    public int maxArea(int mat[][], int n, int m) {
        // add code here.
        Solution s= new Solution();
        int res= s.getMaxArea(mat[0], m);
        for(int i=1;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                if(mat[i][j]==1)
                {
                    mat[i][j]+=mat[i-1][j];
                }
            }
            res=Math.max(res,s.getMaxArea(mat[i], m));
            
        }
        return res;
        
        
        
    }
0
prashanttomar7651 month ago
*YE KAEY NAHI CHALTA HAI JI.*😔😑
*FAILING ON TESTCASE NO. 148*
 
int maxhist(vector<int> arr, int n)   {      vector<long long> right;       stack<pair<long long,long long>> s;       int pseudoindex = n;       for(long long i=n-1; i>=0; i--)       {           if(s.size() == 0)           right.push_back(pseudoindex);           else if(s.size() > 0 && s.top().first < arr[i])           right.push_back(s.top().second);           else if(s.size() > 0 && s.top().first >= arr[i])           {               while(s.size() > 0 && s.top().first >= arr[i])               s.pop();               if(s.size()==0)               right.push_back(pseudoindex);               else               right.push_back(s.top().second);           }           s.push({arr[i],i});       }       reverse(right.begin(),right.end());              while(!s.empty())          s.pop();                 // NSL       vector<long long> left;       pseudoindex = -1;       for(long long i=0; i<n; i++)       {           if(s.size() == 0)           left.push_back(pseudoindex);           else if(s.size() > 0 && s.top().first < arr[i])           left.push_back(s.top().second);           else if(s.size() > 0 && s.top().first >= arr[i])           {               while(s.size() > 0 && s.top().first >= arr[i])               s.pop();               if(s.size()==0)               left.push_back(pseudoindex);               else               left.push_back(s.top().second);           }           s.push({arr[i],i});       }              // NSR - NSL - 1          for(int i=0; i<n; i++)       {           right[i] = right[i] - left[i] - 1;       }              // Area = width * arr[i]              long long ans = INT_MIN;       for(int i=0; i<n; i++)       {           right[i] = right[i] * arr[i];           // Max of area           ans = max(right[i],ans);       }       return ans;   }      int maxArea(int M[MAX][MAX], int n, int m)    {       vector<int> v(m,0);              int ans = INT_MIN;       for(int i=0; i<n; i++)       {           for(int j=0; j<m; j++)           {               if(M[i][j] == 0)               v[j]=0;               else               v[j] = v[j] + M[i][j];           }       ans = max(ans, maxhist(v,m));       }       return ans;   }}; 
 
 
 
 
 
 
-3
imaniket1 month ago
C++ Solution using MAH | O(N*M)
vector<int> SSL(int arr[], int n)
{
    vector<int> ans;
    stack<int> st;
    for (int i = 0; i < n; i++)
    {
        if (st.empty())
            ans.push_back(i - 0 + 1);
        else if (arr[st.top()] < arr[i])
            ans.push_back(i - st.top());
        else if (arr[st.top()] >= arr[i])
        {
            while (!st.empty() && arr[st.top()] >= arr[i])
                st.pop();
            if (st.empty())
                ans.push_back(i - 0 + 1);
            else
                ans.push_back(i - st.top());
        }
        st.push(i);
    }
    return ans;
}

vector<int> SSR(int arr[], int n)
{
    vector<int> ans;
    stack<int> st;
    for (int i = n - 1; i >= 0; i--)
    {
        if (st.empty())
            ans.push_back(n - i);
        else if (arr[st.top()] < arr[i])
            ans.push_back(st.top() - i);
        else if (arr[st.top()] >= arr[i])
        {
            while (!st.empty() && arr[st.top()] >= arr[i])
                st.pop();
            if (st.empty())
                ans.push_back(n - i);
            else
                ans.push_back(st.top() - i);
        }
        st.push(i);
    }
    reverse(ans.begin(), ans.end());
    return ans;
}

int maxHist(int a[], int n)
{
    auto ssl = SSL(a, n);
    auto ssr = SSR(a, n);
    int maxi = INT_MIN;
    for (int i = 0; i < n; i++)
        maxi = max(maxi, a[i] * (ssr[i] + ssl[i] - 1));
    return maxi;
}

int maxArea(int M[MAX][MAX], int n, int m) {
    for (int i = 1; i < n; i++)
        for (int j = 0; j < m; j++)
            if (M[i][j] == 1) M[i][j] += M[i-1][j];
            
    int maxi = INT_MIN;
    for (int i = 0; i < n; i++)
        maxi = max(maxi, maxHist(M[i], m));
    return maxi;
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.