Skip to content

Commit 836586b

Browse files
committed
Update Maximal_Rectangle.cc
Add O(n^2) time solution.
1 parent 362467d commit 836586b

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

Maximal_Rectangle.cc

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,39 @@ class Solution {
3737
}
3838
return ans;
3939
}
40-
};
40+
};
41+
42+
43+
//O(n^2) time solution
44+
class Solution {
45+
public:
46+
int maximalRectangle(vector<vector<char> > &matrix) {
47+
// Start typing your C/C++ solution below
48+
// DO NOT write int main() function
49+
int ret = 0;
50+
int row = matrix.size();
51+
if (row == 0) return ret;
52+
int col = matrix[0].size();
53+
vector<int> dp(col, 0);
54+
stack<int> st;
55+
int tmp;
56+
for (int i = 0; i < row; i++) {
57+
for (int j = 0; j < col; j++) {
58+
dp[j] = (matrix[i][j] == '1') ? (dp[j] + 1) : 0;
59+
while (!st.empty() && dp[j] < dp[ st.top() ]) {
60+
tmp = st.top();
61+
st.pop();
62+
ret = max(ret, dp[tmp] * ((st.empty() ? j : (j - 1 - st.top()))));
63+
}
64+
st.push(j);
65+
}
66+
while (!st.empty()) {
67+
tmp = st.top();
68+
st.pop();
69+
ret = max(ret, dp[tmp] * ((st.empty() ? col : (col - 1 - st.top()))));
70+
}
71+
}
72+
return ret;
73+
}
74+
};
75+

0 commit comments

Comments
 (0)