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 };

 

你可能感兴趣的:(in)