84. Largest Rectangle in Histogram
Problem:
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

The largest rectangle is shown in the shaded area, which has area = 10 unit.
Example:
Input: [2,1,5,6,2,3]
Output: 10
思路:
Solution (C++):
int largestRectangleArea(vector<int>& heights) {
heights.push_back(0);
int max_area = 0, n = heights.size();
vector<int> index;
for (int i = 0; i < n; ++i) {
while (!index.empty() && heights[i] <= heights[index.back()]) {
int h = heights[index.back()];
index.pop_back();
int j = index.empty() ? -1 : index.back();
max_area = max(max_area, (i-j-1) * h);
}
index.push_back(i);
}
return max_area;
}
性能:
Runtime: 8 ms Memory Usage: 10.6 MB
相关链接如下:
知乎:littledy
GitHub主页:https://github.com/littledy
github.io:https://littledy.github.io/
欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可
作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。

浙公网安备 33010602011771号