leetcode.133 最大矩形面积

 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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值