题目描述:
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.
(给定n个非负整数表示柱状图的条高如果每个条的宽度为1,则在柱状图中找到最大矩形的面积。以上是一个柱状图,每个栏的宽度为1,高度= [ 2,1,5,6,2,3 ]。最大矩形显示在阴影区域,面积为10单位。)
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 Largest_Rectangle_in_Histogram {
public static int largestRectangleArea(int[] heights)
{
if(heights.length==0)
return 0;
int result = 0;
//存放的是序列的下标
Stack<Integer> stack = new Stack<Integer>();
for(int i=0;i<heights.length;i++)
{
while(!stack.isEmpty()&&heights[i]<heights[stack.peek()])
{
int index = stack.pop();
int height = heights[index];
//这句话说白了就是如果你是最后一个出栈的,那说明你就是之前最小的数,那么你的宽就是i.
int width = stack.isEmpty()?i:i-stack.peek()-1;
result = Math.max(result,width*height);
}
stack.push(i);
}
while(!stack.isEmpty())
{
int index = stack.pop();
int height = heights[index];
int width = stack.isEmpty()?heights.length:heights.length-stack.peek()-1;
result = Math.max(result,width*height);
}
return result;
}
public static void main(String[] args) {
int heights[] = {2,1,2};
System.out.println(largestRectangleArea(heights));
}
}