zoukankan      html  css  js  c++  java
  • Leetcode 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.
    参考http://www.geeksforgeeks.org/largest-rectangle-under-histogram/,一般方法如下面代码所示
    int largestRectangleArea(vector<int> &height) {
        int maxarea = 0, index = 0, n = height.size();
        stack<int> s;
        while(index < n){
            if(s.empty() || height[s.top()] <= height[index]) s.push(index++);
            else{
                int topIndex = s.top();s.pop();
                int  topOfArea = height[topIndex]*(s.empty() ? index : index-s.top()-1);
                maxarea  = max(topOfArea,maxarea);
            }
        }
        while(!s.empty()){
            int topIndex = s.top();s.pop();
            int  topOfArea = height[topIndex]*(s.empty() ? index : index-s.top()-1);
            maxarea  = max(topOfArea,maxarea);
        }
        return maxarea;    
    }
    View Code
     
    关于本题的一点自己的想法
    将直方图的最高点连起来就会形成如下图类似的有波谷的曲线
    两个波谷之间就是一个局部的凸起的形状(局部直方图构成)
    不同凸起之间会有各自的最大直方图面积,相互之间不会影响(底部波谷与波谷除外),
    求出每个凸起的面积,取最大值
    然后底部波谷之间连线又会构成曲线,求出凸起的面积
    直到最后没有凸起,
    所求的最大面积即位直方图面积
  • 相关阅读:
    mysql的常用函数
    oracle的常用函数
    oracle 11g安装(转)
    Oracle TNS配置浅析
    PL/SQL Developer连接本地Oracle 11g 64位数据库
    mysql之对视图的操作
    mysql之对索引的操作
    mysql之对表的操作
    Mac机装Win7后 启动只见鼠标怎么办
    天高云淡风轻
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3811114.html
Copyright © 2011-2022 走看看