解题思路:
单调栈
代码参考了:
http://www.cnblogs.com/lichen782/p/leetcode_Largest_Rectangle_in_Histogram.html
提交代码:
class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer> stack=new Stack<Integer>();
int[] h=new int[heights.length+1];
h=Arrays.copyOf(heights,heights.length+1);
int i=0;
int pos;
int curSize,maxSize=0;
while(i<h.length) {
if(stack.isEmpty()||h[stack.peek()]<=h[i])
stack.push(i++);
else {
pos=stack.pop();
curSize=stack.isEmpty()?h[pos]*i:h[pos]*(i-stack.peek()-1);
if(curSize>maxSize)
maxSize=curSize;
}
}
return maxSize;
}
}
运行结果:

本文介绍了一种使用单调栈解决LeetCode中最大矩形问题的方法。通过维护一个单调递增的栈,算法能够有效地计算出直方图中最大的矩形面积。代码参考自lichen782的博客,提供了完整的Java实现,并通过了LeetCode的测试。
514

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



