int largestRectArea(vector<int> &h) {
stack<int> p;
int i = 0, m = 0;
h.push_back(0);
while(i < h.size()) {
if(p.empty() || h[p.top()] <= h[i])
p.push(i++);
else {
int t = p.top();
p.pop();
m = max(m, h[t] * (p.empty() ? i : i - p.top() - 1 ));
}
}
return m;
}
初始思路:以该条立柱为最低点的矩形,是该立柱的高乘上他的左边界和右边界的边长。
进行优化为O(n)
开始push进去0,保证至少有最右边的边界值0
1.额外空间栈,只放递增的数字的下标
2.如果为空,push
3.如果大于等于栈顶,push
4.如果小于栈顶,开始计算。(遇到了右边界了),栈pop之后的top为左边界。
自己写的,尽量详细的解法,便于理解
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<int> mystack;
height.push_back(0);
int i=0,result=0;
while(i<height.size())
{
if(mystack.empty()||height[mystack.top()]<=height[i])
{
mystack.push(i++);
}
else
{
int t=mystack.top();
mystack.pop();
if(!mystack.empty())
{
int candidate=height[t]*(i-mystack.top()-1);// left is mystack.top() right is i
result=max(result,candidate);
}
else
{
int candidate=height[t]*(i);//i-(-1)-1 left is -1,right is i
result=max(result,candidate);
}
}
}
return result;
}
};