码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Largest Rectangle in Histogram

时间:2014-06-27 23:01:16      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   width   2014   

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.
bubuko.com,布布扣Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
 
bubuko.com,布布扣
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/,一般方法如下面代码所示
bubuko.com,布布扣
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
 
关于本题的一点自己的想法
将直方图的最高点连起来就会形成如下图类似的有波谷的曲线bubuko.com,布布扣
两个波谷之间就是一个局部的凸起的形状(局部直方图构成)
不同凸起之间会有各自的最大直方图面积,相互之间不会影响(底部波谷与波谷除外),
求出每个凸起的面积,取最大值
然后底部波谷之间连线又会构成曲线,求出凸起的面积
直到最后没有凸起,
所求的最大面积即位直方图面积

Leetcode Largest Rectangle in Histogram,布布扣,bubuko.com

Leetcode Largest Rectangle in Histogram

标签:style   blog   http   color   width   2014   

原文地址:http://www.cnblogs.com/xiongqiangcs/p/3811114.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!