代码随想录算法训练营第六十天 | 84.柱状图中最大的矩形

84.柱状图中最大的矩形

解析:代码随想录

题目:- LeetCode

1. 核心思路就是求左右比中间小的第一个值,所以让单调栈保持单调递增。

2. right = i  - >  mid = ms.pop()  ->  left = ms.peek()

3. width = right - left - 1;   height = heights[mid]

4. w * h = area, 求max area

5. 左右需要加0,解决edge case(看解析

class Solution {
    public int largestRectangleArea(int[] heights) {
        int[] tmp = new int[heights.length + 2];
        //首位加0, 为何加0看解析
        System.arraycopy(heights, 0, tmp, 1, heights.length);
        Stack<Integer> ms = new Stack();
        int max = 0;
        ms.push(tmp[0]);

        for (int i = 1; i < tmp.length; i++) {
            while (tmp[i] < tmp[ms.peek()]) {
                int mid = ms.pop();
                //if (ms.isEmpty()) continue; //因为有0压箱底,所以这步不需要
                int left = ms.peek();
                int area = (i - left - 1) * tmp[mid];
                // System.out.print(i + "  " + mid + "  ");
                // System.out.println(area);
                max = Math.max(max, area);
            }
            ms.push(i);
        }
        return max;
    }
}
//public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
// src denotes the source array.
// srcPos is the index from which copying starts.
// dest denotes the destination array
// destPos is the index from which the copied elements are placed in the destination array.
// length is the length of the subarray to be copied.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值