-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathMaxRectangleInBinaryMatrix.cpp
72 lines (54 loc) · 1.39 KB
/
MaxRectangleInBinaryMatrix.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and return its area.
Bonus if you can solve it in O(n^2) or less.
Example :
A : [ 1 1 1
0 1 1
1 0 0
]
Output : 4
As the max area rectangle is created by the 2x2 rectangle created by (0,1), (0,2), (1,1) and (1,2)
LINK: https://www.interviewbit.com/problems/max-rectangle-in-binary-matrix/
*/
int largestRectangleArea(vector<int> &A)
{
int n = A.size();
int mxarea = 0, i = 0;
stack<int> st;
while(i<n)
{
if(st.empty() || A[st.top()] <= A[i])
st.push(i++);
else
{
int ind = st.top();
st.pop();
int area = A[ind] * (st.empty() ? i : i - st.top() - 1);
mxarea = max(mxarea, area);
}
}
while(!st.empty())
{
int ind = st.top();
st.pop();
int area = A[ind] * (st.empty() ? i : i - st.top() - 1);
mxarea = max(mxarea, area);
}
return mxarea;
}
int Solution::maximalRectangle(vector<vector<int> > &A)
{
int m = A.size();
int n = A[0].size();
int ans = largestRectangleArea(A[0]);
for(int i=1;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(A[i][j]!=0)
A[i][j] += A[i-1][j];
ans = max(ans, largestRectangleArea(A[i]));
}
}
return ans;
}