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

    84. 柱状图中最大的矩形

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

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

     

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

     

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

    示例:

    输入: [2,1,5,6,2,3]
    输出: 10
    public class T84 {
        public int largestRectangleArea(int[] heights) {
            if (heights == null || heights.length == 0) {
                return 0;
            }
            if (heights.length == 1) {
                return heights[0];
            }
            int len = heights.length;
            int[] lefts = new int[len];
            int[] rights = new int[len];
            lefts[0] = -1;
            rights[len - 1] = len;
            for (int i = 1; i < heights.length; i++) {
                int temp = i - 1;
                while (temp >= 0 && heights[temp] >= heights[i]) {
                    temp = lefts[temp];
                }
                lefts[i] = temp;
            }
            for (int i = len - 1; i >= 1; i--) {
                int temp = i + 1;
                while (temp < len && heights[temp] >= heights[i]) {
                    temp = rights[temp];
                }
                rights[i] = temp;
            }
            int res = 0;
            for (int i = 0; i < len; i++) {
                res = Math.max(res, heights[i] * (rights[i] - lefts[i] - 1));
            }
            return res;
        }
    }
    一回生,二回熟
  • 相关阅读:
    CF611C New Year and Domino
    CF706C Hard problem (状态机dp)
    CF467C George and Job (dp)
    Vue的响应式系统
    如何更好的使用js?
    关于JS变量和作用域详解
    运算符的应用及流程控制if,switch语句
    js闭包
    js的基础
    js的使用及语法
  • 原文地址:https://www.cnblogs.com/zzytxl/p/12527606.html
Copyright © 2011-2022 走看看