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;
}
}
本文探讨了如何解决LeetCode中的一道题目——寻找直方图中最大的矩形面积。通过使用栈来存储高度递增的直方图柱子的索引,当遇到比栈顶元素高度小的柱子时,依次弹出栈顶元素并计算面积。该算法复杂度为O(n),对于非负整数表示的直方图高度,能有效找出最大矩形面积。

被折叠的 条评论
为什么被折叠?



