Leetcode 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.


算法:
1. if height[i]>=stack.peek(), push
2. if height[i]< stack.peek(), pop

这题naive的方法就是遍历所有的height,每一个height往两边找最远的点:O(n^2)
对于x, 栈里面保存了左边最远的点(左邻居),而右边最远的点就是当x pop out时,进栈点i的左邻居, 也就是 i-1.
栈里面保存index,才能方便的算出矩形的底边

[code]

public class Solution {
    public int largestRectangleArea(int[] height) {
        Stack<Integer> stack=new Stack<Integer>();
        if(height==null || height.length==0)return 0;
        stack.push(0);
        int i=1, max=0;
        for(i=1;i<height.length;i++)
        {
            int top=stack.peek();
            if(height[top]<=height[i])
            {
                stack.push(i);
            }
            else
            {
                int end=top;
                while(stack.size()>0 && height[stack.peek()]>=height[i])
                {
                    top=stack.pop();
                    max= stack.size()==0 ? Math.max(max, i*height[top]) : Math.max(max, (i-stack.peek()-1)*height[top]);
                }

                stack.push(i);
            }
        }
        if(stack.size()>0)
        {
            int end=stack.peek(), start=end;
            while(stack.size()>0)
            {
                start=stack.pop();
                max= stack.size()==0 ? Math.max(max, (end+1)*height[start]) : Math.max(max, (end-stack.peek())*height[start]);
            }

        }
        return max;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值