84. Largest Rectangle in Histogram

图片描述

For example,
Given heights = [2,1,5,6,2,3],
return 10
要求一个矩形的面积,要知道高和宽。
若是每次肯定高度为height[i], 而后调用一个helper function找到左右边界,即不小于height[i]的最左和最右。
这是一个明显O(N^2)的算法,每次扫描都会重走整个array。
这里有些步骤是没必要要的,好比高度为2往左扫的时候已经知道2>1了,然当高度为1的时候,没必要往左走,咱们能够经过空间来记忆已知信息。
一个递增序列156这种,咱们知道能够够成的矩形是会不断增大的。而当1562,遇到2的时候矩形可能变小,这时咱们就要计算面积了。
递增序列预处理,递减的时候计算。
用代码打印出每步的结果。
height : 0 left :0 right : 1 cur 2 area : 2
height : 3 left :3 right : 4 cur 6 area : 6
height : 2 left :2 right : 4 cur 10 area : 10
height : 5 left :5 right : 6 cur 3 area : 10
height : 4 left :2 right : 6 cur 8 area : 10
height : 1 left :0 right : 6 cur 6 area : 10
public class Solution {
    public int largestRectangleArea(int[] heights) {
        Stack<Integer> stk = new Stack<>();
        int area = 0;
        for(int i=0; i<= heights.length; i++){
            int h = i == heights.length ? 0 : heights[i];
            if(stk.isEmpty() || h >= heights[stk.peek()]){
                stk.push(i);
            } else {
                int top = stk.pop();
                // 为何用stk.peek()+1, 由于这里stack里存的可能不连续。
                area = Math.max(area, heights[top]*(stk.isEmpty()? i: i-(stk.peek()+1)));
                i--;
            }
        }
        return area;
    }
相关文章
相关标签/搜索