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 height = [2,1,5,6,2,3]
,
return 10
.
这道题让求直方图中最大的矩形,刚开始看到求极值问题以为要用DP来做,可是想不出递推式,只得作罢。这道题如果用暴力搜索法估计肯定没法通过OJ,但是我也没想出好的优化方法,在网上搜到了网友水中的鱼的博客,发现他想出了一种很好的优化方法,就是遍历数组,每找到一个局部峰值,然后向前遍历所有的值,算出共同的矩形面积,每次对比保留最大值,代码如下:
解法一:
// Pruning optimize class Solution { public: int largestRectangleArea(vector<int> &height) { int res = 0; for (int i = 0; i < height.size(); ++i) { if (i + 1 < height.size() && height[i] <= height[i + 1]) { continue; } int minH = height[i]; for (int j = i; j >= 0; --j) { minH = min(minH, height[j]); int area = minH * (i - j + 1); res = max(res, area); } } return res; } };
后来又在网上发现一种比较流行的解法,是利用栈来解,可参见网友实验室小纸贴校外版的博客,但是经过仔细研究,其核心思想跟上面那种剪枝的方法有异曲同工之妙,这里维护一个栈,用来保存递增序列,相当于上面那种方法的找局部峰值,当当前值小于栈顶值时,取出栈顶元素,然后计算当前矩形面积,然后再对比当前值和新的栈顶值大小,若还是栈顶值大,则再取出栈顶,算此时共同矩形区域面积,照此类推,可得最大矩形。代码如下:
解法二:
class Solution { public: int largestRectangleArea(vector<int> &height) { int res = 0; stack<int> s; height.push_back(0); for (int i = 0; i < height.size(); ++i) { if (s.empty() || height[s.top()] < height[i]) s.push(i); else { int cur = s.top(); s.pop(); res = max(res, height[cur] * (s.empty() ? i : (i - s.top() - 1))); --i; } } return res; } };
我们可以将上面的方法稍作修改,使其更加简洁一些:
解法三:
class Solution { public: int largestRectangleArea(vector<int>& heights) { int res = 0; stack<int> s; heights.push_back(0); for (int i = 0; i < heights.size(); ++i) { while (!s.empty() && heights[s.top()] >= heights[i]) { int cur = s.top(); s.pop(); res = max(res, heights[cur] * (s.empty() ? i : (i - s.top() - 1))); } s.push(i); } return res; } };
本文转自博客园Grandyang的博客,原文链接:直方图中最大的矩形[LeetCode] Largest Rectangle in Histogram ,如需转载请自行联系原博主。