zoukankan      html  css  js  c++  java
  • 84. 柱状图中最大的矩形

    给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。

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

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

    图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。

    示例:

    输入: [2,1,5,6,2,3]
    输出: 10

    方法1:分治
    class Solution {
        public int largestRectangleArea(int[] heights) {
            //分治 —— 关键,找出最低点
            return getL(heights,0,heights.length - 1);
        }
        
        private int getL(int[] nums,int start,int end){
            if(start > end){
                return 0;
            }
            int index = start;
            for(int i = start;i <= end;i++){
                if(nums[i] < nums[index]) index = i;
            }
            return Math.max(nums[index] * (end - start + 1),Math.max(getL(nums,start,index - 1),getL(nums,index + 1,end)));
        }
    }

     方法2:单调栈

    class Solution {
        public int largestRectangleArea(int[] hei) {
            if(hei == null || hei.length == 0) return 0;
            //单调递增栈
            Stack<Integer> stack = new Stack<>();
            stack.push(-1);
            int res = Integer.MIN_VALUE;
            for(int i = 0;i < hei.length;i++){
                while(stack.peek() != -1 && hei[stack.peek()] >= hei[i]){
                    //处理i - 1前的
                    res = Math.max(res,hei[stack.pop()] * (i - stack.peek() - 1));
                }
                stack.push(i);
            }
            while(stack.peek() != -1){
                res = Math.max(res,hei[stack.pop()] * (hei.length - stack.peek() - 1));
            }
            return res;
        }
    
    }
    一回生,二回熟
  • 相关阅读:
    [解题报告]256 Quirksome Squares
    [解题报告]369 Combinations
    [解题报告]10696 f91
    [解题报告]483 Word Scramble
    [解题报告]10041 Vito's Family
    [解题报告]686 Goldbach's Conjecture (II)
    [解题报告]151 Power Crisis
    [解题报告]10079 Pizza Cutting
    [解题报告]495 Fibonacci Freeze
    [解题报告]541 Error Correction
  • 原文地址:https://www.cnblogs.com/zzytxl/p/12681590.html
Copyright © 2011-2022 走看看