有难度的题目,很难想到是用2个栈实现的,网上搜了解决方案恍然大悟啊!!
来了新的元素如果比当前小,就pop其余栈,索引栈是塞入最前的比它大的元素的索引。
来了新的元素,和当前数字一样大,也是压入栈的,不然会出现错误。
总之是个好题目。
原来以为用动态规划做,想啊想,就是没想到怎么用动态规划做,看来不是所有题目都是可以用动态规划解决的。
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<int> sh;
stack<int> sidx;
int max_area=0;
for(int i=0;i<height.size();i++)
{
if(sh.empty() || sh.top()<=height[i])
{
sh.push(height[i]);
sidx.push(i);
}
else //if(sh.top()>height[i])
{
int j=0;
while(!sh.empty() && sh.top()>height[i])
{
int curh=sh.top();
sh.pop();
j=sidx.top();
sidx.pop();
int area=(i-j)*curh;
if(area>max_area) max_area=area;
}
sh.push(height[i]);
sidx.push(j);
}
}
while(!sh.empty())
{
int j=sidx.top();
sidx.pop();
int h=sh.top();
sh.pop();
int area=(height.size()-j)*h;
if(area>max_area) max_area=area;
}
return max_area;
}
};