Skip to content

Commit d302eaa

Browse files
committed
Largest rectangle in histogram using stack
1 parent 30f1a6d commit d302eaa

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
//Find largest rectangle area in a histogram where height of n bars is given and width of each bar is 1
2+
3+
4+
#include <iostream>
5+
#include <vector>
6+
#include <stack>
7+
#include <vector>
8+
using namespace std;
9+
10+
11+
int largestRectangleArea(vector<int> &A)
12+
{
13+
14+
//Use stack to get next smallest element of each A[i] in there left and right side
15+
//vector pair is used to store index of next smallest for each A[i] in the right and left side of A[i];
16+
17+
const int INF=-1e9;
18+
19+
stack <int> s;
20+
int n=A.size();
21+
vector <pair <int,int> > v;
22+
23+
for(int i=0;i<n;i++)
24+
{
25+
v.push_back({INF,INF});
26+
}
27+
28+
s.push(0);
29+
for(int i=1;i<n;i++)
30+
{
31+
while(!s.empty()&&A[i]<A[s.top()])
32+
{
33+
v[s.top()].first=i;
34+
s.pop();
35+
}
36+
s.push(i);
37+
38+
}
39+
40+
while(!s.empty()){
41+
v[s.top()].first=n;
42+
s.pop();
43+
}
44+
45+
46+
47+
s.push(n-1);
48+
for(int i=n-2;i>=0;i--)
49+
{
50+
while(!s.empty()&&A[i]<A[s.top()])
51+
{
52+
v[s.top()].second=i;
53+
s.pop();
54+
}
55+
s.push(i);
56+
}
57+
58+
while(!s.empty()){
59+
v[s.top()].second=-1;
60+
s.pop();
61+
}
62+
63+
64+
65+
int ans=0;
66+
for(int i=0;i<n;i++)
67+
{
68+
69+
ans=max(ans,A[i]*(v[i].first-v[i].second-1));// using every bar as the height and calculating area of corresponding histogram
70+
71+
72+
}
73+
return ans;
74+
}
75+
76+
int main()
77+
{
78+
int n;
79+
cout << "Enter no of rectangle bars" << endl;
80+
cin >> n;
81+
cout << "Enter hieght of rectangle bars" << endl;
82+
vector <int> a(n);
83+
for(int i=0;i<n;i++)
84+
{
85+
cin >> a[i];
86+
87+
}
88+
89+
cout << "Largest Rectangle area in histogram is " << largestRectangleArea(a) << endl ;
90+
}
91+
//Time Complexity : O(N)
92+
//Space Complexity : O(N)
93+
94+
95+

0 commit comments

Comments
 (0)