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.
Example: |
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。 求在该柱状图中,能够勾勒出来的矩形的最大面积。 以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]。 图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。 示例: 输入: [2,1,5,6,2,3] |
思路:从前往后每选到一个局部峰值(当前高度小于下一个高度,比如图中2,6,3),然后从当前位置往前找最大矩形。也就是找到当前最小高度x宽。
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int res=0;
for(int i=0;i<heights.size();++i)
{
if(i+1<heights.size() && heights[i]<=heights[i+1]) //一定要先判断i在范围内
continue;
int mn=heights[i];
for(int j=i;j>=0;j--)
{
mn=min(mn,heights[j]);
res=max(res,mn*(i-j+1));
}
}
return res;
}
};