Largest Rectangle in Histogram

ref http://www.cnblogs.com/lichen782/p/leetcode_Largest_Rectangle_in_Histogram.html

弹栈天题

public class Solution {
    public int largestRectangleArea(int[] height) {
        int i = 0;
        int res = 0;
        Stack<Integer> st = new Stack<Integer>();
        //padding a new array
        int[] h = new int[height.length+1];
        h = Arrays.copyOf(height, height.length+1); //copyOf(byte[] original, int newLength) Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
        
        while(i<h.length){
            if(st.isEmpty() ||h[i] >= h[st.peek()] ){ // 单调递增stack,存储的是index
             // if(st.isEmpty() ||h[i] >= st.peek() ){
                st.push(i++);
            }else{
                int t = st.pop();           // 发现了比我高的,那就在st里往前退回一步
                res = Math.max(res, h[t]*(st.isEmpty()? i: i-st.peek()-1)); // i-st.peek()这个位置是st里面比h【t】矮的那个点,这个点之后到当前i,都比h【t】高,因此面积就是h【t】*i-st.peek()-1
            }
        }
        return res;
    }
}
//ref http://www.cnblogs.com/lichen782/p/leetcode_Largest_Rectangle_in_Histogram.html
// 类似题目 Longest Valid Parentheses , Maximal Rectangle


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值