LeetCode 84. Largest Rectangle in Histogram

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
if (heights.size() == 0) return 0;
heights.insert(heights.begin(), 0);
heights.push_back(0);
stack<int> s;
s.push(0);
int ans = 0;
for (int i = 1; i < heights.size(); ++i) {
while (heights[i] < heights[s.top()]) {
int h = heights[s.top()]; s.pop();
int w = i - s.top() - 1;
ans = max(ans, h * w);
}
s.push(i);
}
return ans;
}
};