地址
https://www.acwing.com/problem/content/description/832/
描述
思想
动态过程
代码模板
#include <iostream>
#include <stack>
using namespace std;
const int N=1e5+10;
int a[N];
stack<int> s;
int main(){
int n;
cin>>n;
for(int i=0;i<n;i++){
int t;cin>>t;
while(!s.empty()&&t<=s.top()) s.pop();
if(s.empty()) a[i]=-1;
else a[i]=s.top();
s.push(t);
}
for(int i=0;i<n;i++) cout<<a[i]<<" ";
return 0;
}
例题
https://leetcode-cn.com/problems/largest-rectangle-in-histogram/submissions/
描述
思想
代码
class Solution {
public:
int largestRectangleArea(vector<int>& h) {
int n=h.size();
stack<int>s;//存放下标
//left[i]存放i左边比h[i]小的柱子的最近下标。
//right[i]存放i右边比h[i]小的柱子的最近下标。
vector<int> left(n),right(n);
//计算left
for(int i=0;i<n;i++){
while(!s.empty()&&h[i]<=h[s.top()]) s.pop();
if(s.empty()) left[i]=-1;
else left[i]=s.top();
s.push(i);
}
//清空栈
s=stack<int>();
//计算right
for(int i=n-1;i>=0;i--){
while(!s.empty()&&h[i]<=h[s.top()]) s.pop();
//!!!!注意!!!!
//右边和左边不一样
if(s.empty()) right[i]=n;
else right[i]=s.top();
s.push(i);
}
//计算最大面积
int res=0;
for(int i=0;i<n;i++){
res=max(res,h[i]*(right[i]-left[i]-1));
}
return res;
}
};