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

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


猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/80991877