题目描述
有一个直方图,用一个整数数组表示,其中每列的宽度为1,求所给直方图包含的最大矩形面积。比如,对于直方图[2,7,9,4],它所包含的最大矩形的面积为14(即[7,9]包涵的7x2的矩形)。
给定一个直方图A及它的总宽度n,请返回最大矩形面积。保证直方图宽度小于等于500。保证结果在int范围内。
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
.
使用动态规划 n方
class Solution {
public:
int largestRectangleArea(vector<int>& re) {
int n=re.size();
if(n==0)
{
return 0;
}
int sum=numeric_limits<int>::min();
vector<int> dp(n,0);//存储区间内的最小值,只保存一行
for(int i=n-1;i>=0;i--)
{
for(int j=i;j<n;j++)
{
if(i==j)
{
dp[j]=re[i];
sum=max(sum,re[i]);
}
else
{
dp[j]=re[i]<dp[j]?re[i]:dp[j];
sum=max(sum,(j-i+1)*dp[j]);
}
}
}
return sum;
}
};