Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]
.
The largest rectangle is shown in the shaded area, which has area = 10
unit.
For example, given heights = [2,1,5,6,2,3]
, return 10
.
这道题使用单调栈
单调栈,顾名思义,也就是很单调的栈,是一个具有单调性的栈。最简单的单调性就是保持递增或递减,比如 1 2 3 4 就是一个单调的序列,而2 3 4 1则不是。如果要维护一个上升的单调栈,入栈时,如果栈为空或栈顶小于当前元素,则入栈;如果栈顶大于当前元素,则弹出栈顶,直到栈顶小于当前元素或栈为空为止。
每次计算出栈的那个高度的最大矩形
#include <iostream>
#include <cstdio>
#include <stdlib.h>
#include <string>
#include <vector>
#include <stack>
using namespace std;
int main(){
char a[200] = {'0'};
int i = 0;
int j = 0;
int k = 0;
int pos;
int n;
vector<int> box;
stack<int> st;
int res = 0;
int kuan, mian, gao;
int zheng[25] = {0};
int dao[25] = {0};
cin.getline(a, 200, '\n');
for(i = 0; i < 200; i++){
if(a[i] <= '9' && a[i] >= '0'){
box.push_back(a[i] - '0');
}
}
n = box.size();
for(i = 0; i < n; i++){
if(st.empty() || st.top() < box[i]){
st.push(i);
st.push(box[i]);
continue;
}
while(!st.empty() && box[i + n] < st.top()){
//cout << i << "pop" << endl;
gao = st.top();
st.pop();
pos = st.top();
st.pop();
mian = gao * (i - pos);
if(mian > res){
res = mian;
}
}
st.push(pos);
st.push(box[i]);
}
cout << res << endl;
}