题目
Largest Rectangle in Histogram
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
分析
这道题看起来和之前那道**Trapping Rain Water**很像,给的例题都有直方图,但这题要求的是直方图中能找到的最大矩形面积,要求连续的几个数数值越近越好,就能组成更大的面积,与之前那道正好相反。
解法一
首先,最容易想到的解法就是对数组中的每个高度都求出对应的最大矩形面积,然后取最大值,即为答案。
要求固定高度h的最大矩形面积的话,我们需要遍历整个数组,然后记录每一个能够组成的高度为h的矩形面积,最后取最大值,伪代码如下:
for i in heights do
if (heights[i] >= h) //这个元素作为当前矩形的一部分
else //该元素高度小于矩形高度,计算当前矩形面积
需要注意的几点:
- 计算矩形面积后要及时更新矩形的左右下标为初始值
- 当最后一个元素也大于矩形高度时,不能忽略这个矩形的高度
- 为了避免重复计算,可以用map来存储已经计算过的高度对应的面积
代码
class Solution {
public:
int largestRectangleArea(vector<int