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
解题思路
这道题使用栈作为数据结构记录遍历过的坐标位置
算法主要分为两种情况:
- 如果当前位置 i 所对应的 heights[i] 大于栈顶记录的 heights[stack.top()],那么将当前位置入栈
- 否则,从栈顶元素开始,计算所能得到的最大矩形面积。由于栈中保存的是一个递增序列,那么对于每一个栈中记录的位置 stack[p],它的面积就是它对应的高度( heights[stack[p]] )和它所跨越的数组区间的宽度(它的前一个元素( stack[p-1])与当前位置 i 之间的距离 - 1)的乘积。比较最大面积 result 与当前计算得出的面积,取二者的较大值。重复上述操作,直到满足(1)中的条件。
C++代码
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int res = 0, count = 0;
stack<int> rec;
heights.push_back(0);
for(int i = 0; i < heights.size(); ) {
if(rec.empty() || heights[rec.top()] <= heights[i]) {
rec.push(i);
i++;
}
else {
count = rec.top();
rec.pop();
res = max(res, heights[count] * (rec.empty()? i : i - rec.top() - 1));
}
}
return res;
}
};