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
.
思路:
一个比较直观的思路是对于每个直方,分别向左右找到比它小的直方,然后求得从当前位置扩展可得到的最大值。然而这需要O(n^2)的复杂度,其中有很多重复的判断。
可以使用一个栈来实现上述思路。当栈为空或者栈顶元素小于当前值时,把当前值压入栈中,否则的话相当于找到了右边界,再从栈中弹出元素,因为栈内元素是递增的,所以弹出来的相当于是左边界。逐个计算面积,更新当前的max值,直到栈顶元素大于当前元素为止。弹栈时需要注意栈为空的情况。
代码:
1 int max(int a, int b){ 2 if(a > b) 3 return a; 4 return b; 5 } 6 int largestRectangleArea(vector<int> &height) { 7 // IMPORTANT: Please reset any member data you declared, as 8 // the same Solution instance will be reused for each test case. 9 stack<int> Stack; 10 int size = height.size(); 11 if(size == 0) 12 return 0; 13 int i = 0; 14 int maxRec = 0; 15 while(i < size){ 16 if(Stack.empty() || height[Stack.top()] <= height[i]){ 17 Stack.push(i++); 18 } 19 else{ 20 int t = Stack.top(); 21 Stack.pop(); 22 int tmpRec = height[t]*(Stack.empty()?i:i-Stack.top()-1); 23 if(tmpRec > maxRec) 24 maxRec = tmpRec; 25 } 26 } 27 while(!Stack.empty()){ 28 int t = Stack.top(); 29 Stack.pop(); 30 int tmpRec = height[t]*(Stack.empty()?i:i-Stack.top()-1); 31 if(tmpRec > maxRec) 32 maxRec = tmpRec; 33 } 34 return maxRec; 35 }