zoukankan      html  css  js  c++  java
  • 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.

    分析:设置一个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 };
  • 相关阅读:
    [比赛|考试]9.21上午考试
    给花_Q
    [比赛|考试] 9.17下午考试
    [比赛|考试]nowcoder NOIP提高组组第二场
    图论
    生成函数
    P4197 Peaks
    3942: [Usaco2015 Feb]Censoring
    P2245 星际导航
    P3565 [POI2014]HOT-Hotels
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4445441.html
Copyright © 2011-2022 走看看