# Maximal Rectangle in C++

Suppose we have a 2D binary matrix where 0s and 1 values are present. We have to find the largest rectangle containing only 1s and return its area.

To solve this, we will follow these steps−

• Define a function called getAns, this will take array a

• create stack st, i := 0, ans := 0

• while i < size of a, then

• if stack is empty or a[i] >= top of stack, then insert i into st, increase i by 1

• otherwise −

• height := a[top of stack], delete from stack

• width := i when stack is empty, otherwise i – top of st – 1

• area := height * width

• ans := max of ans and area

• while st is not empty

• height := a[top of st], delete from stack

• width := size of a when st is empty, otherwise size of a – top of st – 1

• area := height * width

• ans := max of ans and area

• return ans

• From the main method do the following −

• ans := 0, n := size of x

• if n zero, then return 0

• m := size of x[0]

• create one array height of size m

• for i in range 0 to n – 1

• for j in range 0 to m – 1

• if x[i, j] = 1, then increase height[j] by 1, otherwise height[j] := 0

• ans := max of ans and getAns(height)

• return ans

## Example (C++)

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int getAns(vector <int> a){
stack <int> st;
int i = 0;
int ans = 0;
while(i<a.size()){
if(st.empty()||a[i]>=a[st.top()]){
st.push(i);
i++;
} else{
int height = a[st.top()];
st.pop();
int width = st.empty()?i:i-st.top()-1;
int area = height * width;
ans = max(ans,area);
}
}
while(!st.empty()){
int height = a[st.top()];
st.pop();
int width = st.empty()?a.size():a.size() - st.top()-1;
int area = height * width;
ans = max(ans,area);
}
return ans;
}
int maximalRectangle(vector<vector<char>>& x) {
int ans = 0;
int n = x.size();
if(!n)return 0;
int m = x[0].size();
vector <int> height(m);;
for(int i =0;i<n;i++){
for(int j =0;j<m;j++){
if(x[i][j] == '1')height[j]++;
else height[j] = 0;
}
ans = max(ans, getAns(height));
}
return ans;
}
};
main(){
vector<vector<char>> v = {
{'1','0','1','0','0'},
{'1','0','1','1','1'},
{'1','1','1','1','1'},
{'1','0','0','1','0'}
};
Solution ob;
cout << (ob.maximalRectangle(v));
}

## Input

{{'1','0','1','0','0'},
{'1','0','1','1','1'},
{'1','1','1','1','1'},
{'1','0','0','1','0'}
}

## Output

6