[InterviewBit] Maximum Size Square Sub-matrix

Maximum Size Square Sub-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;
A.push_back(0);
vector<pair<int, int>> st;
for(int i = 0; i < A.size(); i++) {
int p = i;
while(st.size() and st.back().second >= A[i]) {
int h = st.back().second, w = (i - st.back().first);
res = max(res, min(h,w) * min(h,w));
p = st.back().first;
st.pop_back();
}
st.push_back({p, A[i]});
}

return res;
}

int Solution::solve(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/11/01/PS/interviewbit/maximum-size-square-sub-matrix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.