-
Notifications
You must be signed in to change notification settings - Fork 4
/
85-Maximal Rectangle.cpp
65 lines (52 loc) · 1.48 KB
/
85-Maximal Rectangle.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
64
65
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
int m = matrix.size();
if(m==0) return 0;
int n = matrix[0].size();
int result = 0;
vector<int> h(n,0);
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(matrix[i][j] == '0'){
h[j] = 0;
}else{
h[j]++;
}
}
result = max(result, largestArea(h));
}
return result;
}
int largestArea(vector<int> &h){
int area = 0;
stack<int> s;
int n = h.size();
for(int i = 0 ; i < n ; i++){
while(!s.empty() && h[s.top()] >= h[i]){
int top = s.top();
s.pop();
int start;
if(s.empty()){
start = -1;
}else{
start = s.top();
}
area = max(area , h[top]*(i - start - 1));
}
s.push(i);
}
while(!s.empty()){
int top = s.top();
s.pop();
int start;
if(s.empty()){
start = -1;
}else{
start = s.top();
}
area = max(area, h[top] *(n - start -1));
}
return area;
}
};