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

Largest Rectangle in Histogram*****

时间:2015-04-21 22:06:27      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

分析:设置一个stack,保存柱状图递增区间的标号,如例子中保存1,2,3,直到i=4时height[4]=2打破了一直递增的状态,因此,弹出top的元素,计算面积为6;若stack不为空或者当前元素小于等于stack中的top元素,则一直弹出top元素并更新面积的最大值。遇到末尾我们添加的-1时,由于已经没有元素比-1小,所以开始弹出stack中的元素,同时计算面积并更新最大值。参考至hackersun007的博客。运行时间31ms

 1 class Solution {
 2 public:
 3     int largestRectangleArea(vector<int>& height) {
 4         height.push_back(-1);
 5         stack<int> index;
 6         int i = 0, result = 0;
 7         while(i < height.size()){
 8             if(index.empty() || height[i] > height[index.top()])
 9                 index.push(i++);
10             else{
11                 int temp = index.top();
12                 index.pop();
13                 result = max(result, height[temp] * (index.empty() ? i :(i-index.top()-1)));
14             }
15         }
16         return result;
17     }
18 };

 

Largest Rectangle in Histogram*****

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4445441.html

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