-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path**85-MaximalRectangle.cpp
63 lines (46 loc) · 1.52 KB
/
**85-MaximalRectangle.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
class Solution {
public:
int calculateMaxRectangle(vector<int> V){
stack<int> stk;
int len = V.size(), i = 0, answer = 0;
while(i < len){
if(stk.empty() || V[stk.top()] < V[i]){
stk.push(i++);
} else {
int ind = stk.top();
stk.pop();
// compute height.
int candidate = V[ind] * ((stk.empty())? i: i - stk.top() - 1 );
answer = (candidate > answer)? candidate: answer;
}
}
while(!stk.empty()){
int ind = stk.top();
stk.pop();
// compute height.
int candidate = V[ind] * ((stk.empty())? i: i - stk.top() - 1 );
answer = (candidate > answer)? candidate: answer;
}
return answer;
}
int maximalRectangle(vector<vector<char>>& M) {
int rows = M.size();
if(rows == 0) return 0;
int cols = M[0].size();
vector<vector<int>> TC (rows, vector<int> (cols, 0));
int answer = 0;
for(int i = 0; i < cols; i++) TC[0][i] = M[0][i] == '1';
for(int i = 1; i < rows; i++){
for(int j = 0; j < cols; j++){
TC[i][j] = (M[i][j] == '1') ? TC[i-1][j] + 1: 0;
}
}
for(int i = 0; i < rows; i++){
int max_rectangle = calculateMaxRectangle(TC[i]);
if(max_rectangle > answer){
answer = max_rectangle;
}
}
return answer;
}
};