lintcode(122)直方图最大矩形覆盖

Description:

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.

histogram

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

histogram

The largest rectangle is shown in the shaded area, which has area = 10 unit.

Explanation:

给出 height = [2,1,5,6,2,3],返回 10

Solution:

计算以当前值为高的矩形面积,所以要找到它的左右边界。建立栈,存储当前元素在数组中的位置。将数组元素一次推入栈中,如果它比栈顶元素小,则栈顶元素的右边界出现了,现在确定他的左边界。此时将栈顶元素出栈。栈中都是比当前元素小的值,因为比当前值大的都因当前值而出栈,所以,可以借此确定当前矩形的左边界,如果栈为空,说明当前元素是栈中最小值,左边界就是0。知道左右边界之后就可以计算面积了,高度是当前值,宽度是 i 或者 i-stack.peek()-1,为什么再-1?因为是左边界,已经不在矩形范围内了,当前值已经出栈了。

public class Solution {
    /**
     * @param height: A list of integer
     * @return: The area of largest rectangle in the histogram
     */
    public int largestRectangleArea(int[] height) {
        // write your code here
        if(height.length == 0) return 0;
        
        int[] high = Arrays.copyOf(height , height.length + 1);
        
        int result = 0;
        Stack<Integer> rank = new Stack<Integer>();
        for(int i = 0;i<high.length;i++){
            while(!rank.isEmpty() && high[i] < high[rank.peek()] ){
                int area = high[rank.pop()]*(rank.isEmpty()?i:i-rank.peek() - 1);
                result = Math.max(result , area);
            }
            rank.push(i);
        }
        
        return result;
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值