• Largest Rectangle in Histogram


    Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

    Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

    The largest rectangle is shown in the shaded area, which has area = 10 unit.

    For example,
    Given height = [2,1,5,6,2,3],
    return 10.

    思路:先新建两个数组left和right,left数组用于保存每个矩形的最左边开始的可以和当前矩形形成矩形的最小下标,

    right数组用于保存每个矩形的最右边开始的可以和当前矩形形成矩形的最大下标。

    最后,根据最左最右下标的差值相乘矩形的高度值,求出矩形的最大值。

     1 class Solution {
     2 public:
     3     int max (int a, int b)
     4 {
     5     return a > b ? a : b;
     6 }
     7 int largestRectangleArea(vector<int>& height) {
     8     int n = height.size();
     9     int *left,*right,next,i;
    10     left = (int*)malloc(n * sizeof(int));
    11     right = (int*)malloc(n * sizeof(int));
    12     left[0] = -1;
    13     right[n-1] = n;
    14     for (i=1; i < n; i++){
    15         if (height[i-1] < height[i]){
    16             left[i] = i-1;
    17         }else {
    18             next = i-1;
    19             while (left[next] != -1 && height[left[next]] >= height[i])
    20                 next = left[next];
    21             left[i] = left[next];
    22         }
    23     }
    24     for (i=n-2; i >= 0; i--){
    25         if (height[i+1] < height[i]){
    26             right[i] = i+1;
    27         }else {
    28             next = i+1;
    29             while (right[next] != n && height[right[next]] >= height[i])
    30                 next = right[next];
    31             right[i] = right[next];
    32         }
    33     }
    34     int largest = 0;
    35     for (i=0 ;i < n; i++){
    36         largest = max(largest,height[i] * (right[i]-left[i]-1));
    37     }
    38     return largest;
    39         }
    40 };
  • 相关阅读:
    .net软件反编译笔记
    Asp.Net 网站一键部署技术(上)
    C# TreeGridView 实现进程列表
    HeidiSQL Navicat
    Flask项目中邮箱模块的应用
    如何在已有的Flask项目添加数据表结构?
    把u盘刻录成系统盘
    Object '<Tbl_next_week_change_state at 0x7f2c78d849e8>' is already attached to session '4' (this is '6')
    OSError: [Errno 98] Address already in use
    Linux下设置和查看环境变量
  • 原文地址:https://www.cnblogs.com/george-cw/p/4489173.html
Copyright © 2020-2023  润新知