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.
大致题意:给一个数组,数组的值为柱状图的高度,求其中最大的面积(宽度为1)
自己写的O(n^2) 就不献丑了,这里有一个O(n), 原文:https://www.geeksforgeeks.org/largest-rectangle-under-histogram/
思路:从头到尾遍历,求 以h(x)(0 <= x <=n) (第x个柱子的高度)为最小高度 的矩形的最大面积。(有点绕嘴- . -),那么需要知道前边第一个比h(x)小的柱子的坐标的下一个(前引索) 和 最后边第一个比h(x)小的柱子的坐标的上一个(后引索)。(说的有点乱)。。比如!!!
求以第5个柱子为最小高度的最大面积 , 那么我们可以看到,前引索为2(第三个柱子),后引索为5(第六个柱子),面积为(5-2+1)*2.
就这样,遍历一遍找出最大面积。
问题的关键就是找出前后引索,伪算法:
循环(i < l):
新建一个栈(储存引索,而不是数组的值)
if 如果栈空 或者 遍历到的柱子高度 >= 栈顶引索对应的柱子高度
则入栈; i++; (这样入栈,造成一个单调递增栈)
else 如果 遍历到的柱子高度 < 栈顶引索对应的柱子高度 ( 因为i对应的柱子比前一个矮,所以后引索为 i ) 注意!!! 下边没有i++!!!!
记录栈顶引索;(因为栈单调递增,所以前引索就是第一个)
栈顶出栈;
有前后引索,计算面积;
具体代码(C++):
#include<iostream>
#include<stack>
using namespace std;
int getMaxArea(int hist[], int n)
{
stack<int> s;
int max_area = 0;
int tp;
int area_with_top;
int i = 0;
while (i < n)
{
if (s.empty() || hist[s.top()] <= hist[i])
s.push(i++);
else
{
tp = s.top();
s.pop();
area_with_top = hist[tp] * (s.empty() ? i : i - s.top() - 1);
if (max_area < area_with_top)
max_area = area_with_top;
}
}
while (s.empty() == false) //如果没有遍历完
{
tp = s.top();
s.pop();
area_with_top = hist[tp] * (s.empty() ? i :
i - s.top() - 1);
if (max_area < area_with_top)
max_area = area_with_top;
}
return max_area;
}