84. Largest Rectangle in Histogram
Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
题目解析:
- 对于某一列,找到左边第一个小于它的列和右边第一个小于它的列,使用单调递增栈
- 需要考虑两端边界的情况,所以需要在左右两端各加一个高度为0的列
代码:
class Solution {
public int largestRectangleArea(int[] heights) {
int[] newHeights = new int[heights.length + 2];
newHeights[0] = 0;
newHeights[newHeights.length - 1] = 0;
for (int i = 0; i < heights.length; i++) {
newHeights[i+1] = heights[i];
}
int maxArea = 0;
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < newHeights.length; i++) {
while (!stack.isEmpty() && newHeights[stack.peek()] > newHeights[i]) {
int mid = stack.pop();
int left = stack.peek();
int w = i - left - 1;
int h = newHeights[mid];
maxArea = Math.max(maxArea, w * h);
}
stack.push(i);
}
return maxArea;
}
}