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 heights = [2,1,5,6,2,3],
return 10.
这个题暴力解法肯定是超时。
化繁为简
先假设后面的都比前面的大,如下图,那就容易计算了。
但是如果碰到前面比后面大的情况,就可以先将和前面比它大的全部都比较一遍,然后放入栈中,直到栈里的所有元素都是递增的。
代码如下:
public int largestRectangleArea(int[] height) {
int area = 0;
java.util.Stack<Integer> heightStack = new java.util.Stack<Integer>();
java.util.Stack<Integer> indexStack = new java.util.Stack<Integer>();
for (int i = 0; i < height.length; i++) {
if (heightStack.empty() || heightStack.peek() <= height[i]) {
heightStack.push(height[i]);
indexStack.push(i);
}
else if(heightStack.peek() > height[i]) {
int j = 0;
while (!heightStack.empty() && heightStack.peek() > height[i]) {
j = indexStack.pop();
int currArea = (i - j) * heightStack.pop();
if (currArea > area) {
area = currArea;
}
}
heightStack.push(height[i]);
indexStack.push(j);
}
}
while (!heightStack.empty()) {
int currArea = (height.length - indexStack.pop()) * heightStack.pop();
if (currArea > area) {
area = currArea;
}
}
return area;
}
如果我们遇到这道题的时候,一开始应该想想特例,比如递增序列下的最大矩形面积,然后发散开来,想想一般情况和这种递增情况的关系,也许就能有突破。使用类似的”从特例到一般”的发散方式还有Candy (分糖果)的第二种解法。