Skip to content

Commit 867c0ab

Browse files
committed
Largest rectangle area under histogram added
1 parent feabb75 commit 867c0ab

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
/*
2+
Given the heights of the bars of a histogram, find out the largest
3+
rectangular area under the histogram. Width of each bar is 1 unit.
4+
*/
5+
6+
#include <bits/stdc++.h>
7+
using namespace std;
8+
9+
// Prints largest rectangular area under histogram
10+
void largestAreaUnderHistogram(int height[], int n)
11+
{
12+
13+
// Stores index of the bars
14+
stack<int> s;
15+
int ans = 0;
16+
int l = 0, r = 0;
17+
for (int i = 0; i < n; i++)
18+
{
19+
20+
// If stack is empty, push the bar
21+
if (s.empty())
22+
{
23+
s.push(i);
24+
continue;
25+
}
26+
27+
// If height[i] is greater then push the bar
28+
if (height[i] > height[s.top()])
29+
{
30+
s.push(i);
31+
}
32+
else
33+
{
34+
// I have encountered a height that is less than my last height
35+
36+
// Pop out all bars whose height is greater than height[i],
37+
// Simulataneously calculate the new area
38+
while (!s.empty() && height[i] < height[s.top()])
39+
{
40+
int toBeRemoved = s.top();
41+
s.pop();
42+
int area;
43+
if (s.empty())
44+
{
45+
area = height[toBeRemoved] * i;
46+
}
47+
else
48+
{
49+
area = height[toBeRemoved] * (i - s.top() - 1);
50+
}
51+
//cout << toBeRemoved << " " << area << endl;
52+
if (area > ans)
53+
{
54+
ans = area;
55+
l = (!s.empty()) ? s.top() : 0;
56+
r = i;
57+
}
58+
ans = max(ans, area);
59+
}
60+
s.push(i);
61+
}
62+
}
63+
cout << "Largest area = " << ans << " between bars " << l << " and " << r;
64+
}
65+
66+
int main()
67+
{
68+
69+
// Input number of bars
70+
cout << "Enter number of bars: ";
71+
int n;
72+
cin >> n;
73+
// Input heights
74+
cout << "Enter height of each bar: ";
75+
int height[n];
76+
for (int i = 0; i < n; i++)
77+
cin >> height[i];
78+
79+
largestAreaUnderHistogram(height, n);
80+
}
81+
82+
/*
83+
Time Complexity: O(n)
84+
Space Complexity: O(n)
85+
86+
SAMPLE INPUT AND OUTPUT
87+
Enter number of bars: 7
88+
Enter height of each bar: 6 2 5 4 5 1 6
89+
Largest area = 12 between bars 1 and 5
90+
*/

0 commit comments

Comments
 (0)