给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
示例 1:
输入:heights = [2,1,5,6,2,3] 输出:10 解释:最大的矩形为图中红色区域,面积为 10
示例 2:
输入: heights = [2,4] 输出: 4
提示:
1 <= heights.length <=105
0 <= heights[i] <= 104
int largestRectangleArea(vector<int>& heights) {
vector < std:: pair<int, int > > vec;//index,value
int maxInt = heights[0] ;
vec.push_back(std::pair<int, int >{ 0, heights[0] });
for (int i = 1; i<heights.size(); i++)
{
if (heights[i]<vec[vec.size() - 1].second)
{
vec.push_back(std::pair<int, int >{i, heights[i]});
//遇到小的计算区间的
for (int m = 0; m<vec.size(); m++)
{
std::pair<int, int > firstV = vec[m];
for (int n = vec.size() - 1; n>m; n--)
{
std::pair<int, int > secondV = vec[n];
int tmp = std::min(firstV.second,secondV.second)*(secondV.first - firstV.first + 1);
if (tmp <= maxInt && n != vec.size() - 1)
{
break;
}
if (tmp > maxInt)
{
maxInt = tmp;
}
}
}
//调整数组
while (vec.size() > 0)
{
int len = vec.size()-1;
if (len == 0)
{
vec[len].second = heights[i];
break;
}
if (len-1>=0 && vec[len].second >= heights[i] && vec[len-1].second < heights[i])
{
vec[len].second = heights[i];
break;
}
else
{
vec.pop_back();
continue;
}
}
}
else
{
if (heights[i]>maxInt)
{
maxInt = heights[i];
}
vec.push_back(std::pair<int, int >{i,heights[i]});
}
}
//遇到小的计算区间的
for (int m = 0; m<vec.size(); m++)
{
std::pair<int, int > firstV = vec[m];
for (int n = vec.size() - 1; n>m; n--)
{
std::pair<int, int > secondV = vec[n];
int tmp = std::min(firstV.second, secondV.second)*(secondV.first - firstV.first + 1);
if (tmp < maxInt)
{
break;
}
maxInt = tmp;
}
}
return maxInt;
}