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
.
public class Solution {
public int largestRectangleArea(int[] height) {
if(height == null || height.length == 0)
return 0;
int maxArea = height[0];
for(int i = 1; i < height.length; i++){
if(i < height.length - 1 && height[i] <= height[i + 1])
continue;
int minHeight = height[i];
for(int j = i; j >= 0; j--){
minHeight = Math.min(height[j], minHeight);
maxArea = Math.max(maxArea, minHeight * (i - j + 1));
}
}
return maxArea;
}
}
O(n)的解法只能看大神的,确实神,不过不是很难理解。
可以知道每一个最大area一定会包含至少一个完整的hist。这样如果用这个完整的hist的高度去求面积,只要知道宽度就行了。如果现在有几个从左往右递增的高度,那么把这些index存到一个stack里。直到遇到第一个height小于stack顶元素的hist,则开始一个一个的pop出stack的元素并以当前stack顶元素作为最小的高度求面积。
看这里的解说吧,明白一些。
public class Solution {
public int largestRectangleArea(int[] height) {
if(height == null || height.length == 0)
return 0;
int maxArea = height[0];
Stack<Integer> s = new Stack<Integer>();
int i = 0;
while(i < height.length){
if(s.isEmpty() || height[i] >= height[s.peek()]){
s.push(i);
i++;
}
else{
int top = s.pop();
int area = height[top] * (s.isEmpty() ? i : (i - s.peek() - 1));
maxArea = Math.max(maxArea, area);
}
}
while(!s.isEmpty()){
int top = s.pop();
int area = height[top] * (s.isEmpty() ? i : (i - s.peek() - 1));
maxArea = Math.max(maxArea, area);
}
return maxArea;
}
}