cpp
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int size = heights.size();
int n = heights.size();
vector<int> left(size, -1);
stack<int> st;
st.push(0);
//找到每个柱子左侧小于它高度的最近元素的下标
for(int i = 1; i < size; i++){
while(!st.empty() && heights[st.top()] >= heights[i])
st.pop();
if(!st.empty())
left[i] = st.top();
st.push(i);
}
vector<int> right(size, n);
stack<int> st2;
st2.push(n - 1);
//找到每个柱子左侧小于它高度的最近元素的下标
for(int i = n - 2; i >= 0; i--){
while(!st2.empty() && heights[st2.top()] >= heights[i])
st2.pop();
if(!st2.empty())
right[i] = st2.top();
st2.push(i);
}
int res = 0;
for(int i = 0; i < size; i++){
res = max(res, heights[i] * (right[i] - left[i] - 1));
}
return res;
}
};