84. Largest Rectangle in Histogram(直方图最大面积 hard)

时间:2023-03-10 06:41:33
84. Largest Rectangle in Histogram(直方图最大面积  hard)

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.

84. Largest Rectangle in Histogram(直方图最大面积  hard)

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

84. Largest Rectangle in Histogram(直方图最大面积  hard)

The largest rectangle is shown in the shaded area, which has area = 10 unit.

For example,
Given heights = [2,1,5,6,2,3],
return 10.

用桟

 class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer> stack = new Stack<Integer>(); //array 扩容,在最后一位加上0
int[] a = new int[heights.length+1];
for(int i =0;i<heights.length;i++)
a[i] = heights[i];
a[heights.length]=0;
// int answer = 0;
int temp;
for(int i = 0;i<a.length;){
if(stack.isEmpty()||a[i]>a[stack.peek()]){//a[i]与桟顶元素比较
stack.push(i);
i++;
}
else{
temp = stack.pop();
answer = Math.max(answer,a[temp]*(stack.isEmpty()?i: i-stack.peek()-1));
//桟为空的时候,需要计算长度为i 高度从0到i最矮的(即桟中最小的元素,弹出后,桟就空了)
}
}
return answer;
}
}