单调栈,首位各插入一个0,避免讨论栈为空的情况
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int ans=0;
stack<int>st;
//首位各自插入0,避免了讨论栈是否为空
heights.insert(heights.begin(),0);
heights.push_back(0);
for(int i=0;i<heights.size();i++)
{
while(!st.empty()&&heights[st.top()]>heights[i])
{
int cur=st.top();
st.pop();
ans=max(ans,(i-st.top()-1)*heights[cur]);
}
st.push(i);
}
return ans;
}
};