Skip to content

Commit 0cf1039

Browse files
committed
Feb 1
1 parent 979594a commit 0cf1039

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

**85-MaximalRectangle.cpp

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
class Solution {
2+
public:
3+
4+
int calculateMaxRectangle(vector<int> V){
5+
stack<int> stk;
6+
7+
int len = V.size(), i = 0, answer = 0;
8+
9+
while(i < len){
10+
11+
if(stk.empty() || V[stk.top()] < V[i]){
12+
stk.push(i++);
13+
} else {
14+
int ind = stk.top();
15+
stk.pop();
16+
17+
// compute height.
18+
int candidate = V[ind] * ((stk.empty())? i: i - stk.top() - 1 );
19+
answer = (candidate > answer)? candidate: answer;
20+
}
21+
22+
}
23+
24+
while(!stk.empty()){
25+
int ind = stk.top();
26+
stk.pop();
27+
28+
// compute height.
29+
int candidate = V[ind] * ((stk.empty())? i: i - stk.top() - 1 );
30+
answer = (candidate > answer)? candidate: answer;
31+
}
32+
33+
return answer;
34+
}
35+
36+
int maximalRectangle(vector<vector<char>>& M) {
37+
int rows = M.size();
38+
if(rows == 0) return 0;
39+
int cols = M[0].size();
40+
41+
vector<vector<int>> TC (rows, vector<int> (cols, 0));
42+
43+
int answer = 0;
44+
45+
for(int i = 0; i < cols; i++) TC[0][i] = M[0][i] == '1';
46+
47+
for(int i = 1; i < rows; i++){
48+
for(int j = 0; j < cols; j++){
49+
TC[i][j] = (M[i][j] == '1') ? TC[i-1][j] + 1: 0;
50+
}
51+
}
52+
53+
54+
for(int i = 0; i < rows; i++){
55+
int max_rectangle = calculateMaxRectangle(TC[i]);
56+
if(max_rectangle > answer){
57+
answer = max_rectangle;
58+
}
59+
}
60+
61+
return answer;
62+
}
63+
};

0 commit comments

Comments
 (0)