
这个题目的核心在于,当小柱子出现时,长柱子的结果立马可以被确定,可以归类为,找右边第一个小于自己的元素,从而规约到单调栈解法。
cpp
typedef pair<int, int> P;
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int ans = 0;
vector<P> st{P(-1, -1)};
heights.push_back(-1);
int n = heights.size();
for(int i=0;i<n;i++)
{
int h = heights[i];
int mi = i;
while(h < st.back().first)
{
ans = max(ans, st.back().first*(i-st.back().second));
mi = st.back().second;
st.pop_back();
}
st.push_back(P(h, mi));
}
return ans;
}
};