原题网址:https://leetcode.com/problems/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 heights = [2,1,5,6,2,3]
,
return 10
.
方法:使用一个栈来维持递增的直方柱。
public class Solution {
public int largestRectangleArea(int[] heights) {
int max = 0;
Stack<Integer> stack = new Stack<>();
for(int i=0; i<heights.length; i++) {
while (!stack.isEmpty() && heights[stack.peek()] > heights[i]) {
int p = stack.pop();
int width = stack.isEmpty()? i : i-stack.peek()-1;
int area = heights[p] * width;
max = Math.max(max, area);
}
stack.push(i);
}
while (!stack.isEmpty()) {
int p = stack.pop();
int width = stack.isEmpty()? heights.length : heights.length-stack.peek()-1;
int area = heights[p] * width;
max = Math.max(max, area);
}
return max;
}
}