题目链接
关键:利用单调栈确定有效矩形边界
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int n = heights.size();
//找到当前元素两端 最近且比它小的元素 // 中间就是有效区域(!不包括两端点)
vector<vector<int> >info(n,vector<int>(2));
stack<int>st; //大压小单调栈
for(int i=0;i<n;i++){
//出栈时结算
while(!st.empty() && heights[i]<heights[st.top()]){
int t = st.top();
st.pop();
info[t][1] = i;
if(st.empty()) info[t][0] = -1; //表示没找到
else info[t][0] = st.top();
}
st.push(i);
}
//遍历完后,结算栈内剩余元素
while(!st.empty()){
int t = st.top();
info[t][1] = -1;
st.pop();
if(st.empty()) info[t][0] = -1;
else info[t][0] = st.top();
}
//信息收集完毕
int maxx = 0;
for(int i=0,l,r;i<n;i++){
if(info[i][0] == -1){
l = -1; //都是比该位置大
}else{
l = info[i][0];
}
if(info[i][1] == -1){
r = n ; //向两端最大延伸到的下标
}else{
r = info[i][1];
}
// l+1 - r-1
maxx = max(maxx, (r-l-1)* heights[i]);
}
return maxx;
}
};