【C++】单调栈求最大矩形面积

选做题(单调栈的应用):

给定n个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为1。求在该柱状图中,能够勾勒出来的矩形的最大面积。

    图 1 柱状图示例

图1是柱状图的示例,给定的高度为,所能勾勒出来的矩形如图2所示,这些矩形最大面积为10(对应从左数第3个矩形)。

                                                                  图 2 所能勾勒出来的矩形

样例输入:

2 1 5 6 2 3

样例输出:

10

//单调栈的应用
//author:Mitchell_Donovan
//date:3.23
#include<iostream>
using namespace std;

class arrayStack {
private:
	int size;
	int top;
	int** stack;
public:
	arrayStack(int sizeValue) {
		size = sizeValue;
		stack = new int* [size];
		for (int i = 0; i < size; i++) {
			stack[i] = new int[2];
			stack[i][0] = stack[i][1] = -1;
		}
		top = 0;
	}
	~arrayStack() {
		for (int i = 0; i < size; i++) {
			delete[]stack[i];
		}
		delete[]stack;
	}
	bool push(int rank, int number) {
		if (top == size - 1) {
			cout << "The stack has been full!" << endl;
			return false;
		}
		top += 1;
		stack[top][0] = rank;
		stack[top][1] = number;
		return true;
	}
	bool pop() {
		if (top == 0) {
			cout << "The stack is empty!" << endl;
			return false;
		}
		stack[top][0] = stack[top][1] = -1;
		top -= 1;
		return true;
	}
	void getmax(int*array,int arraySize) {//2 1 4 4 5 1 3
		int area = 0;
		for (int i = 0; i < arraySize; i++) {
			if (array[i] > stack[top][1]) {
				push(i, array[i]);
			}
			else if (array[i] < stack[top][1]) {
				while (array[i] < stack[top][1]) {
					int height = stack[top][1];
					int width = i - stack[top - 1][0] - 1;
					area = max(height * width, area);
					pop();
				}
				push(i, array[i]);
			}
		}
		cout <<"The largest area is "<< area << endl;
	}
};
int main() {
	int arraySize;
	cout << "Please input the number of rectangles:";
	cin >> arraySize;
	int* array = new int[arraySize + 2];
	array[0] = 0;
	cout << "Please input the value of each rectangle:";
	for (int i = 1; i < arraySize + 1; i++) {
		cin >> array[i];
	}
	array[arraySize + 1] = 0;
	arrayStack test(arraySize + 2);
	test.getmax(array, arraySize + 2);
}

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mitch311

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值