Skip to content

Commit f119dea

Browse files
authored
MAH variation
1 parent ae7cfcc commit f119dea

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

Diff for: Stack/13 Max area rectangle in Binary matrix.cpp

+92
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
//https://leetcode.com/problems/maximal-rectangle/
2+
class Solution {
3+
public:
4+
int largestRectangleArea(vector<int>& heights) {
5+
int n= heights.size();
6+
vector<int> left,right;
7+
stack<pair<int,int>> s1,s2;
8+
int pseudo_index =-1;
9+
int pseudo_index1 =n;
10+
for (int i=0;i<n;i++)
11+
{
12+
if (s1.size()==0)
13+
{
14+
left.push_back(pseudo_index);
15+
}
16+
else if (s1.size()>0 && s1.top().first<heights[i])
17+
{
18+
left.push_back(s1.top().second);
19+
}
20+
else if (s1.size()>0 && s1.top().first>=heights[i])
21+
{
22+
while(s1.size()>0 && s1.top().first>=heights[i])
23+
{
24+
s1.pop();
25+
}
26+
if (s1.size()==0)
27+
{
28+
left.push_back(pseudo_index);
29+
}
30+
else
31+
{
32+
left.push_back(s1.top().second);
33+
}
34+
}
35+
s1.push({heights[i],i});
36+
}
37+
for (int i=n-1;i>=0;i--)
38+
{
39+
if (s2.size()==0)
40+
{
41+
right.push_back(pseudo_index1);
42+
}
43+
else if (s2.size()>0 && s2.top().first<heights[i])
44+
{
45+
right.push_back(s2.top().second);
46+
}
47+
else if (s2.size()>0 && s2.top().first >= heights[i])
48+
{
49+
while(s2.size()>0 && s2.top().first >= heights[i])
50+
{
51+
s2.pop();
52+
}
53+
if (s2.size()==0)
54+
{
55+
right.push_back(pseudo_index1);
56+
}
57+
else
58+
{
59+
right.push_back(s2.top().second);
60+
}
61+
}
62+
s2.push({heights[i],i});
63+
}
64+
reverse(right.begin(),right.end());
65+
int m=INT_MIN;
66+
for (long long i=0;i<n;i++)
67+
{
68+
m=max(m,(right[i]-left[i]-1)*heights[i]);// taking max after finding area
69+
}
70+
return m;
71+
}
72+
73+
int maximalRectangle(vector<vector<char>>& matrix) {
74+
int m=matrix.size();
75+
if(m==0) return 0;
76+
int n=matrix[0].size(), result=0;
77+
vector<int> histogram(n, 0);
78+
79+
for(int i=0; i<m; i++){
80+
for(int j=0; j<n; j++){
81+
if(matrix[i][j]=='1')
82+
histogram[j]+=1;
83+
else
84+
histogram[j]=0;
85+
}
86+
87+
result = max(result, largestRectangleArea(histogram));
88+
cout<<result<<" ";
89+
}
90+
return result;
91+
}
92+
};

0 commit comments

Comments
 (0)