Largest Rectangle in Histogram
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.
Analysis
分析:
- 对于每一个bar 'x', calculate the area with 'x' as the smallest bar
- 比较所有面积取最大 方法:
- find index of first smaller than 'x' bar on the left: left index
- find index of first smaller than 'x' bar on the left: right index 实现:
- traverse all bars from left to right, maintain a stack of bars
- every bar pushed to stack once
- bar popped from stack when a bar of smaller height is seen
- when bar popped, calculate the area with popped bar as smallest bar
- current index: right index
- index of previous item: left index
Code
public class Solution {
public int largestRectangleArea(int[] height) {
int len = height.length;
Stack<Integer> s = new Stack<Integer>();
int maxArea = 0;
for(int i = 0; i <= len; i++){
int h = (i == len ? 0 : height[i]);
if(s.isEmpty() || h >= height[s.peek()]){
s.push(i);
//一旦找到一个height更小的,说明stack top的右边界找到了.此时如果stack empty,那么左边界是index=-1, 如果不是empty,左边界是上一个push在stack里面的index
//因为在左边比它大bar已经处理过了,剩下的一定是比它小的bar,最上面一个就是离它最近比它小的bar
}else{
int tp = s.pop();
maxArea = Math.max(maxArea, height[tp] * (s.isEmpty() ? i : i - 1 - s.peek()));
i--;
}
}
return maxArea;
}
}
Note
- Not fully understand, need re-think