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
原文链接: https://www.cnblogs.com/dysjtu1995/p/12315862.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;
也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/329882
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!