.
- [503. 下一个更大元素 II](https://leetcode-cn.com/problems/next-greater-element-ii/)
- [84. 柱状图中最大的矩形](https://leetcode-cn.com/problems/largest-rectangle-in-histogram/submissions/)
- [85. 最大矩形](https://leetcode-cn.com/problems/maximal-rectangle/)
503. 下一个更大元素 II
#define debug(x) cout<<#x<<": "<<(x)<<endl;
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& a) {
stack<int> st;
int n = a.size();
vector<int> ret(n,-1);
deque<int> qu;
qu.push_back(0);
for(int i=1;i<n;++i){
if(a[i] <= a[qu.back()]){
qu.push_back(i);
}else{
while( !qu.empty() && a[i] > a[qu.back()] ){
ret[qu.back()] = a[i];
qu.pop_back();
}
qu.push_back(i);
}
}
for(int i=0;i<n;++i){
if(i==qu.back()){
break;
}
if(a[i] <= a[qu.back()]){
qu.push_back(i);
}else{
while( !qu.empty() && a[i] > a[qu.back()] ){
ret[qu.back()] = a[i];
qu.pop_back();
}
}
}
return ret;
}
};
84. 柱状图中最大的矩形
class Solution {
public:
int largestRectangleArea(vector<int>& h) {
stack<int> st;
int ret = 0;
int n = h.size();
for(int i=0;i<n;++i){
if(st.empty() || h[i] >= h[st.top()]){
st.push(i);
}else{
while(!st.empty() && h[i] < h[st.top()] ){
int hei = h[st.top()];
st.pop();
int wid = i;
if(!st.empty()){
wid = wid - st.top() -1;
}
ret = max(ret,hei*wid);
}
st.push(i);
}
}
while(!st.empty()){
int hei = h[st.top()];
st.pop();
int wid = n;
if(!st.empty()){
wid = wid - st.top() -1;
}
ret = max(ret,hei*wid);
}
return ret;
}
};
85. 最大矩形
class Solution {
public:
int maximalRectangle(vector<vector<char>>& a) {
int n = a.size();
int m = a[0].size();
vector<int> h(m,0);
int ret=0;
for(int i=0;i<n;++i){
for(int j=0;j<m;++j){
if( a[i][j] == '0' ){
h[j] = 0;
}else{
h[j] += 1;
}
}
stack<int> st;
for(int j=0;j<m;++j){
if(st.empty() || h[j] >= h[st.top()]){
st.push(j);
}else{
while( !st.empty() && h[j] < h[st.top()] ){
int hei = h[st.top()];
st.pop();
int wid = j;
if(!st.empty()){
wid = wid - st.top() - 1;
}
ret = max(ret,hei*wid);
}
st.push(j);
}
}
while(!st.empty()){
int hei = h[st.top()];
st.pop();
int wid = m;
if(!st.empty()){
wid = wid - st.top() - 1;
}
ret = max(ret,hei*wid);
}
}
return ret;
}
};