• 84. 柱状图中最大的矩形


    1. 柱状图中最大的矩形
      leetcode 困难题
      给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。

    求在该柱状图中,能够勾勒出来的矩形的最大面积。

    以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/largest-rectangle-in-histogram
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    class Solution {
        public int largestRectangleArea(int[] heights) {
            int max = 0;
            Stack<Integer> stack = new Stack<>();
            stack.push(-1);
            for(int i=0;i<heights.length;i++){
                // 待入栈 heights[i]
                while(stack.peek()!=-1&&(heights[stack.peek()]>=heights[i])){//代入栈的数小于栈顶元素
                    //求栈顶元素的最大面积
                    max = Math.max(max, heights[stack.pop()] * (i - stack.peek() -1) );
                }
                stack.push(i);
            }
    
            //栈不为空则
            while(stack.peek()!=-1){
                max = Math.max(max,heights[stack.pop()]*(heights.length-stack.peek()-1));
            }
            return max;
        }
    }
    
  • 相关阅读:
    在排序数组中查找元素
    搜索旋转排序数组
    下一个排列
    括号生成(回溯法)
    PHP之表单
    PHP之超级全局变量
    PHP之数组
    PHP之字符串
    PHP之常量
    PHP之echo/print
  • 原文地址:https://www.cnblogs.com/ZCWang/p/12901165.html
Copyright © 2020-2023  润新知