详细的解释可以看下下面链接的博客
http://www.cnblogs.com/hxsyl/archive/2012/08/16/2643015.html
class Solution {
private:
struct node{
int width;
int height;
};
public:
int largestRectangleArea(vector<int>& heights) {
stack<node> s;
int totalw;
int maxarea=0;
for(int i=0;i<heights.size();i++)
{
if(s.empty())
{
node a;
a.height=heights[i];
a.width=1;
s.push(a);
}
else
{
if(heights[i]>=s.top().height)
{
node a;
a.height=heights[i];
a.width=1;
s.push(a);
}
else
{
totalw=0;
while(!s.empty()&&s.top().height>heights[i])
{
totalw+=s.top().width;
int area=totalw*s.top().height;
maxarea=maxarea>area?maxarea:area;
s.pop();
}
node a;
a.height=heights[i];
a.width=totalw+1;
s.push(a);
}
}
}
totalw=0;
while(!s.empty())
{
totalw+=s.top().width;
int area=totalw*s.top().height;
maxarea=maxarea>area?maxarea:area;
s.pop();
}
return maxarea;
}
};