原题网址: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;
}
}

本文介绍了一种利用栈解决直方图中寻找最大矩形面积的问题的方法。通过维护一个递增的直方柱栈,算法能够高效地找到给定直方图中的最大矩形面积。
278

被折叠的 条评论
为什么被折叠?



