给定整型数组,其中每个元素表示木板的高度,木板的宽度都相同,求这些木板拼出的最大矩形的面积。并分析时间复杂度。

该博客介绍了如何在给定的整型数组中,利用木板高度信息求解最大矩形面积的问题。通过创建一个栈来辅助计算,实现了在非递减高度木板中找到最大矩形面积的算法,并分析了时间复杂度。示例代码展示了具体的实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定整型数组,其中每个元素表示木板的高度,木板的宽度都相同,求这些木板拼出的最大矩形的面积。并分析时间复杂度。
#include <iostream>
#include <stack>
using namespace std;

typedef struct Node {
	int w;
	int h;
} Node; /* 矩形结构 */

stack<Node*> mystack;

Node** initNodeArr(int *arr, int len) {
	Node** nodeArr = new Node*[len];
	for (int i = 0; i < len; ++i) {
		Node * node = new Node();
		node->w = 1;
		node->h = arr[i];
		nodeArr[i] = node;
	}
	return nodeArr;
}

int findMaxRectangleArea(int *arr, int len) {
	if (!arr) {
		return 0;
	}
	Node** nodeArr = initNodeArr(arr, len);
	int curArea = 0;
	int maxArea = 0;
	int totalWidth = 0;

	for (int i = 0; i < len; ++i) {
		if (mystack.empty()) {
			mystack.push(nodeArr[i]);
		} else {
			//栈内元素高度非线性递增
			if (mystack.top()->h <= nodeArr[i]->h) {
				mystack.push(nodeArr[i]);
			} else {
				/*当插入元素小于栈顶, 需要整合,将大于插入元素高的元素出栈,
				 * 并以插入元素高度为准,宽度为出栈个数+插入元素宽度,
				 * 整合为新矩形*/
				totalWidth = 0;
				while (!mystack.empty()) {
					if (mystack.top()->h > nodeArr[i]->h) {
						totalWidth += mystack.top()->w;
						mystack.pop();
					} else {
						break;
					}
				}
				totalWidth += nodeArr[i]->w;
				nodeArr[i]->w = totalWidth;
				mystack.push(nodeArr[i]);
			}
		}
	}

	//计算最大面积
	totalWidth = 0;
	while (!mystack.empty()) {
		totalWidth += mystack.top()->w;
		if ((curArea = totalWidth * mystack.top()->h) > maxArea) {
			maxArea = curArea;
		}
		mystack.pop();
	}

	return maxArea;
}

int main() {
	int arr[] = { 5, 4, 3, 2, 4, 5, 0, 7, 8, 4, 6 };

	cout << "maxArea: "
			<< findMaxRectangleArea(arr, sizeof(arr) / sizeof(arr[0]));

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值