[InterviewBit] Max Rectangle in Binary Matrix

Max Rectangle in Binary Matrix

  • Time :
  • Space :
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
int helper(vector<int>& A) {
int res = 0;
vector<pair<int, int>> st;
A.push_back(0);
for(int i = 0; i < A.size(); i++) {
int p = i;
while(!st.empty() and st.back().first >= A[i]) {
auto [h,pos] = st.back(); st.pop_back();
res = max(res, h * (i - pos));
p = pos;
}
if(A[i]) st.push_back({A[i],p});
}
A.pop_back();

return res;
}

int Solution::maximalRectangle(vector<vector<int> > &A) {
int n = A.size(), m = A[0].size(), res = 0;
vector<int> dp(m);
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(A[i][j]) dp[j] += 1;
else dp[j] = 0;
}
res = max(res, helper(dp));
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/09/PS/interviewbit/max-rectangle-in-binary-matrix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.