Problem:
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
.
这个有很详细的讨论,
http://www.geeksforgeeks.org/largest-rectangle-under-histogram/。时间复杂度为O(n)。
Solution:
public class Solution {
public int largestRectangleArea(int[] height) {
if(height==null||height.length==0)
return 0;
Stack<Integer> st = new Stack<>();
int max = 0;
for(int i=0;i<=height.length;i++)
{
if(i<height.length&&(st.empty()||height[st.peek()]<=height[i]))
{
st.push(i);
}
else
{
int tmp1 = height[st.peek()];
while(!st.empty()&&(i>=height.length||height[st.peek()]>height[i]))
{
int tmp2 = height[st.pop()];
int area = (st.empty()?i:(i-st.peek()-1))*Math.min(tmp1, tmp2);
if(area>max)
max = area;
}
st.push(i);
}
}
return max;
}
}
public int largestRectangleArea(int[] height) {
if(height==null||height.length==0)
return 0;
Stack<Integer> st = new Stack<>();
int max = 0;
for(int i=0;i<=height.length;i++)
{
if(i<height.length&&(st.empty()||height[st.peek()]<=height[i]))
{
st.push(i);
}
else
{
int tmp1 = height[st.peek()];
while(!st.empty()&&(i>=height.length||height[st.peek()]>height[i]))
{
int tmp2 = height[st.pop()];
int area = (st.empty()?i:(i-st.peek()-1))*Math.min(tmp1, tmp2);
if(area>max)
max = area;
}
st.push(i);
}
}
return max;
}
}