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 heights = [2,1,5,6,2,3]
,
return 10
.
这题我看了《算法问题实战策略》想到以前看到过就按照上面的代码ac了
因为代码不算纯自己写的我们先po上来看吧
首先我们把问题分成3种情况
1.最大的矩形在左边
2.最大的矩形在右边
3.最大的矩形在中间
主要处理第三种情况
int Max(int a,int b)
{
return a>b?a:b;
}
int Min(int a,int b)
{
return a<b?a:b;
}
int slove(int *h,int left,int right)
{
if(left==right) return h[left];
int mid=(right-left)/2+left;
int res=Max(slove(h,left,mid),slove(h,mid+1,right));
int lo=mid;
int hi=mid+1;
int height=Min(h[lo],h[hi]);
res=Max(res,height*2);
while(left<lo||hi<right)
{
if(hi<right&&(lo==left||h[lo-1]<h[hi+1]))
{
++hi;
height=Min(height,h[hi]);
}
else
{
--lo;
height=Min(height,h[lo]);
}
res=Max(res,height*(hi-lo+1));
}
return res;
}
int largestRectangleArea(int* heights, int heightsSize)
{
if(heightsSize==0)
{
return NULL;
}
int res=slove(heights,0,heightsSize-1);
return res;
}