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

● 今日学习的文章链接和视频链接

题目84. 柱状图中最大的矩形

● 看到题目的第一想法

完结撒花

● 看完代码随想录之后的想法

和接雨水差不多,就是从比大变成比小

● 实现过程中遇到哪些困难

前后加0没想到

● 解题代码

  1. 点击查看代码
    class Solution {
        public int largestRectangleArea(int[] heights) {
            int len = heights.length;
            int result = 0;
            Stack<Integer> stack = new Stack<>();
            // 数组扩容,在头和尾各加入一个元素
            int [] newHeights = new int[heights.length + 2];
            newHeights[0] = 0;
            newHeights[newHeights.length - 1] = 0;
            for (int index = 0; index < heights.length; index++){
                newHeights[index + 1] = heights[index];
            }
    
            heights = newHeights;
            len = heights.length;
            stack.push(0);
            for(int i = 1;i < len;i++){
                if(heights[i] >= heights[stack.peek()]){
                    stack.push(i);
                }else{
                    while(heights[i] < heights[stack.peek()]){
                        int mid = stack.peek();
                        stack.pop();
                        int left = stack.peek();
                        int right = i;
                        int h = heights[mid];
                        int w = right - left - 1;
                        result = Math.max(result,w * h);
                    }
                    stack.push(i);
                }
            }
            return result;
        }
    }
    

● 今日收获,学习时长

今日收获:柱状图中最大的矩形,结束了一刷,不错不错进步很多
学习时长:30min
posted @ 2024-01-27 10:40  雨年今天有记录吗  阅读(2)  评论(0)    收藏  举报