LeetCode84 Largest Rectangle in Histogram 直方图中的最大矩阵 C++

本文介绍了一种求解直方图中最大矩形面积的问题,提供了两种解决方案:递归法和堆栈法,并详细解释了堆栈法的具体实现过程。

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

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.

 

Example:

Input: [2,1,5,6,2,3]
Output: 10

题源:here;完整实现:here

思路:

两种方案:1 递归;2 堆栈

1 递归

我们按照最小的数将输入分为前后两部分,如此递归的寻找最大值。但是这样会导致内存使用过大,有些用例会溢出,代码如下:

void getMaxRec(vector<int> heights, int &maxRec){
	if (heights.size() == 0) return;
	auto minHeight = min_element(heights.begin(), heights.end());
	int rec = *minHeight*heights.size();
	maxRec = max(maxRec, rec);
	int minIdx = distance(heights.begin(), minHeight);
	if (heights.size() == 1) return;

	vector<int> leftHeights, rightHeights;
	leftHeights.assign(heights.begin(), heights.begin() + minIdx);
	getMaxRec(leftHeights, maxRec);
	rightHeights.assign(heights.begin()+minIdx+1, heights.end());
	getMaxRec(rightHeights, maxRec);
}
int largestRectangleArea(vector<int>& heights) {
	int maxRec = 0;
	getMaxRec(heights, maxRec);
	return maxRec;
}

2 堆栈

这种方法非常靠技巧,需要细致的思考,但是实现方法很简单:我们维持一个stack,里面的数只能是升序,当遇到降序时就记录下前面升序的序列所围成的矩形面积。代码如下:

int largestRectangleArea2(vector<int>& heights){
	stack<int> records; int maxRec = 0;
	heights.push_back(0);
	for (int i = 0; i < heights.size(); i++){
		if (records.size() == 0 || heights[records.top()] <= heights[i]){
			records.push(i); continue;
		}

		int top = records.top(); records.pop();
		int rec = records.size() ? (i - records.top()-1)*heights[top] : i*heights[top];
		maxRec = max(maxRec, rec);
		i--;
	}

	return maxRec;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值