题目:
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.
For example,
Given height = [2,1,5,6,2,3]
,
return 10
.
分析:利用动态规划的思想。先定义两个两个数组 l[i] ,r[i]分别表示height[i]两边第一个小于height[i]之前的数的位置。
代码如下:
int largestRectangleArea(vector<int> &height) {
int n=height.size();
int *l=new int [n];
int *r=new int [n];
for(int i=0;i<n;i++)
{
l[i]=i;
while(l[i]>0&&height[l[i]-1]>=height[i])
{
l[i]=l[l[i]-1];
}
}
for(int i=n-1;i>=0;i--)
{
r[i]=i;
while(r[i]<n-1&&height[r[i]+1]>=height[i])
{
r[i]=r[r[i]+1];
}
}
int result=0;
for(int i=0;i<n;i++)
{
if((r[i]-l[i]+1)*height[i]>result)
{
result=(r[i]-l[i]+1)*height[i];
}
}
delete []l;
delete []r;
return result;
}