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

链接: 84.柱状图中最大的矩形

84.柱状图中最大的矩形

这道题为单调递减的单调栈文章来源地址https://uudwc.com/A/V6zXJ

class Solution {
    public int largestRectangleArea(int[] heights) {
            int res = 0;
            Stack<Integer> stack = new Stack<>();
            stack.push(0);  
            // 首尾添0
            int[] newH = new int[heights.length + 2];
            newH[0] = 0;
            newH[newH.length - 1] = 0;
            System.arraycopy(heights, 0, newH, 1, heights.length);

            for(int i = 1; i < newH.length; i++){
                if(newH[i] > newH[stack.peek()]){
                    stack.push(i);
                }else if(newH[i] == newH[stack.peek()]){
                    stack.pop();
                    stack.push(i);
                }else{
                    while(!stack.isEmpty() && newH[i] < newH[stack.peek()]){
                        int mid = stack.pop();
                        if(!stack.isEmpty()){
                            int left = stack.peek();
                            int right = i;
                            int w = right - left -1;
                            int h = newH[mid];
                            res = Math.max(res, w*h);
                        }
                    }
                    stack.push(i);
                }
                
            }
            return res;
    }
}

原文地址:https://blog.csdn.net/dreams00/article/details/133218945

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请联系站长进行投诉反馈,一经查实,立即删除!

h
上一篇 2023年09月24日 02:29
uniapp 音视频应用及注意事项
下一篇 2023年09月24日 02:29