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.
思路:本体最直接的想法就是遍历每一种情况,通过比较来获得矩形的最大值。如何更快地获得各种情况,我们先从特殊情况考虑,假设所有的方阵高度是递增的,那么我们只需要考虑每一个方阵到最右端方阵所形成的矩形大小就可以了。我们就构造一种递增的序列来求得以每一个方阵为高的矩形面积。
网上有人想到了使用栈的方式。将高较小的均放入栈中,一旦遇见高大的,就出栈并按照递增方式的面积求法得到一个面积,取最大值,将我们现在正在比较的方阵入栈,注意入栈时应该是出栈了多少个就该入栈几次正在比较的方阵,这样是为了自求面积是获得以此方阵为高的矩形的最大面积。
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int area = 0;
stack<int>temp;
for (int i = 0; i < heights.size(); i++) {
if (temp.empty() || temp.top() <= heights[i]) {
temp.push(heights[i]);
} else {
int k = 0;
while (!temp.empty() && temp.top() > heights[i]) {
k++;
area = max(area, temp.top() * k);
temp.pop();
}
while (k--) {
temp.push(heights[i]);
}
temp.push(heights[i]);
}
}
int k = 1;
while (!temp.empty()) {
area = max(area, temp.top() * k);
k++;
temp.pop();
}
return area;
}
};