Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b4c1669

Browse files
largest rectangle in histogram (#277)
largest rectangle in histogram
2 parents 841b357 + 52d5073 commit b4c1669

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)

AltStyle によって変換されたページ (->オリジナル) /