Skip to content

Commit 52d5073

Browse files
committed
largest rectangle in histogram
1 parent 630e0ff commit 52d5073

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include <iostream>
2+
#include <vector>
3+
4+
using namespace std;
5+
6+
int largestRectangleArea(vector<int>& heights)
7+
{
8+
heights.push_back(0);
9+
int n = heights.size();
10+
stack<int> stk;
11+
int ans = 0;
12+
for (int i = 0; i < n; i++) {
13+
if (stk.empty() || heights[stk.top()] <= heights[i])
14+
stk.push(i);
15+
else {
16+
while (!stk.empty() && heights[stk.top()] > heights[i]) {
17+
int barHeight = heights[stk.top()];
18+
stk.pop();
19+
int area = 0;
20+
if (stk.empty())
21+
area = i * barHeight;
22+
else
23+
area = (i - 1 - (stk.top() + 1) + 1) * barHeight;
24+
ans = max(ans, area);
25+
}
26+
stk.push(i);
27+
}
28+
}
29+
return ans;
30+
}
31+
32+
int main() {
33+
vector<int> array;
34+
35+
int number;
36+
37+
while (cin >> number) {
38+
array.push_back(number);
39+
}
40+
41+
cout << largestRectangleArea(array) << endl;
42+
43+
return 0;
44+
}

0 commit comments

Comments
 (0)