Advertisement
imashutosh51

Maximum rectangle containing 1 in binary matrix

Jul 23rd, 2022 (edited)
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.19 KB | None | 0 0
  1. /*
  2. Logic:
  3. If we consider each row as a base and then find the maximum reactangle in histogram then you will get the maximum
  4. rectange from the binary matrix.
  5.  
  6. */
  7. int largest_rectangle(int arr[],int n) {
  8.        stack<pair<int,int>> st;
  9.        st.push({0,-1});
  10.        int ans=INT_MIN;
  11.        for(int i=1;i<n;i++){
  12.            while(st.size() && arr[st.top().first]>=arr[i]){
  13.                ans=max((i-st.top().second-1)*arr[st.top().first],ans);
  14.                st.pop();
  15.            }
  16.            if(st.size()==0){
  17.                st.push({i,-1});
  18.            }
  19.            else{
  20.                st.push({i,st.top().first});
  21.            }
  22.        }
  23.         while(st.size()){
  24.             ans=max(ans,(n-st.top().second-1)*arr[st.top().first]);
  25.             st.pop();
  26.         }
  27.         return ans;
  28. }
  29. class Solution{
  30.   public:
  31.     int maxArea(int arr[MAX][MAX], int n, int m) {
  32.         int ans=INT_MIN;
  33.         for(int i=0;i<n;i++){
  34.             if(i!=0){
  35.                 for(int j=0;j<m;j++)
  36.                 if(arr[i][j]!=0) arr[i][j]+=arr[i-1][j];
  37.                 else arr[i][j]=0;
  38.             }
  39.             ans=max(ans,largest_rectangle(arr[i],m));
  40.         }
  41.         return ans;
  42.     }
  43. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement