84-柱状图的最大矩形

单调栈

class Solution {
    public int largestRectangleArea(int[] heights) {
    	//核心思想:以h[i]为高的矩形的宽等于i左右两边第一个小于h[i]之间的距离
        //单调栈
        int len = heights.length, area = 0;
        Deque<Integer> st = new LinkedList<>();
        //添加哨兵
        int[] newHeight = new int[len+2];
        for(int i = 0;i < len;i++){
            newHeight[i+1] = heights[i];
        }
        newHeight[0] = 0;newHeight[len+1] = 0;
        len += 2;

        st.push(newHeight[0]);
        for(int i = 0;i < len;i++){
            while(newHeight[st.peek()] > newHeight[i]){//当栈顶元素比当前元素大时,说明以栈顶元素为高的矩形宽已经找到了
                int height = newHeight[st.pop()];//出栈
                int width = i - st.peek() - 1;
                area = Math.max(area, height*width);
            }
            st.push(i);
        }
        return area;

        //核心思想:以h[i]为高的矩形的宽等于i左右两边第一个小于h[i]之间的距离
        //暴力法 超时
        // int n = heights.length, ans = 0;
        // for(int i = 0;i < n;i++){
        //     int minHeight = heights[i];
        //     int left = i, right = i;
        //     while(left-1 >= 0 && heights[left-1] >= minHeight)
        //         left--;
        //     while(right+1 < n && heights[right+1] >= minHeight)
        //         right++;
        //     ans = Math.max(ans, minHeight*(right - left + 1));
        // }
        // return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值