LeetCode:Largest Rectangle in Histogram(update)

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.

 

别人家的巧妙的代码:每次都维护一个递增的栈 比较栈顶与当前元素。如果当前元素小于栈顶元素,则入栈,否则合并现有栈,直至栈顶元素小于当前元素。结尾时

入栈元素为0,重复合并一次。

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

 

posted @ 2015-08-05 16:28  尾巴草  阅读(140)  评论(0编辑  收藏  举报