-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathmaximal-rectangle.cpp
More file actions
71 lines (71 loc) · 1.73 KB
/
maximal-rectangle.cpp
File metadata and controls
71 lines (71 loc) · 1.73 KB
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
66
67
68
69
70
71
class Solution {
public:
int largestRectangleArea(vector<int>& arr) {
stack<int>s;
int n=arr.size();
vector<int> rl(n);
rl[n-1]=n;
s.push(n-1);
for(int i=n-2;i>=0;i--){
while(!s.empty() && arr[s.top()]>=arr[i]){
s.pop();
}
if(s.empty()){
rl[i]=n;
}
else{
rl[i]=s.top();
}
s.push(i);
}
stack<int>s1;
vector<int> ll(n);
ll[0]=-1;
s1.push(0);
for(int i=1;i<n;i++){
while(!s1.empty() && arr[s1.top()]>=arr[i]){
s1.pop();
}
if(s1.empty()){
ll[i]=-1;
}
else{
ll[i]=s1.top();
}
s1.push(i);
}
int ans=0;
for(int i=0;i<n;i++){
ans=max(ans, (rl[i]-ll[i]-1)*arr[i]);
}
return ans;
}
int maximalRectangle(vector<vector<char>>& arr) {
int m=arr.size();
if(m==0){
return 0;
}
int n=arr[0].size();
if(n==0){
return 0;
}
vector<vector<int>> ans(m,vector<int>(n,0));
int maximal=0;
for(int i=0;i<n;i++){
ans[0][i]=arr[0][i]-'0';
}
maximal=max(maximal,largestRectangleArea(ans[0]));
for(int i=1;i<m;i++){
for(int j=0;j<n;j++){
if(arr[i][j]=='0'){
ans[i][j]=0;
}
else{
ans[i][j]=ans[i-1][j]+1;
}
}
maximal=max(maximal,largestRectangleArea(ans[i]));
}
return maximal;
}
};