Skip to content

Commit 160f46b

Browse files
committed
Largest Rectangle in Histogram
1 parent 6023ee7 commit 160f46b

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

Stack/LargestRectangleInHistogram.cpp

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#include <iostream>
2+
#include <stack>
3+
#include <vector>
4+
using namespace std;
5+
6+
int largestRectangleArea(vector<int> &heights)
7+
{
8+
int n = heights.size();
9+
vector<int> left(n, 0); // left smaller nearst
10+
vector<int> right(n, 0); // right smaller nearst
11+
stack<int> s;
12+
13+
// right smaller
14+
for (int i = n - 1; i >= 0; i--)
15+
{
16+
while (s.size() > 0 && heights[s.top()] >= heights[i]) // removing invlaid values
17+
{
18+
s.pop();
19+
}
20+
21+
right[i] = s.empty() ? n : s.top();
22+
23+
s.push(i);
24+
}
25+
26+
while (!s.empty()) // to remove previous stack element
27+
{
28+
s.pop();
29+
}
30+
31+
// left smaller
32+
for (int i = 0; i < n; i++)
33+
{
34+
while (s.size() > 0 && heights[s.top()] >= heights[i]) // removing invlaid values
35+
{
36+
s.pop();
37+
}
38+
39+
left[i] = s.empty() ? -1 : s.top();
40+
41+
s.push(i);
42+
}
43+
44+
int ans = 0;
45+
for (int i = 0; i < n; i++)
46+
{
47+
int width = right[i] - left[i] - 1;
48+
int currArea = heights[i] * width;
49+
ans = max(ans, currArea);
50+
}
51+
52+
return ans;
53+
}
54+
55+
int main()
56+
{
57+
vector<int> arr = {2, 1, 5, 6, 2, 3};
58+
59+
cout << largestRectangleArea(arr) << endl;
60+
61+
return 0;
62+
}

Stack/LargestRectangleInHistogram.exe

94 KB
Binary file not shown.

0 commit comments

Comments
 (0)