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 the where width of each bar is 1, given height = [2,1,5,6,2,3] .
The largest rectangle is shown in the shaded area, and which has an area = 10 unit.
For example,
Given height = [2,1,5,6,2,3] ,
Return 10 .
First think of one of the most intuitive methods: The plane as a large matrix, bar as 1, non-bar as 0, looking for the largest total 1 matrix.
The idea is correct, you can use DP to do, but will time out.
On the Internet to see a way with the help of the stack, the code is very beautiful, but the explanation is very vague, I read, decided to carefully describe the following ideas:
1. What should I do if the height array is known to be ascending?
Like 1,2,5,7,8.
So that's (1*5) vs. (2*4) vs. (5*3) vs. (7*2) vs. (8*1)
That is Max (height[i]* (size-i))
2, the purpose of using the stack is to construct such ascending sequence, according to the above method solution.
But the height itself is not necessarily ascending, how should the stack be built?
Like 2,1,5,6,2,3.
(1) 2 into the stack. S={2}, result = 0
(2) 1:2 Small, does not meet the ascending condition, so 2 pops up and records the current result as 2*1=2.
Replace 2 with 1 to re-enter the stack. s={1,1}, result = 2
(3) 5:1 large, meet the ascending conditions, into the stack. S={1,1,5},result = 2
(4) 6:5 large, meet the ascending conditions, into the stack. S={1,1,5,6},result = 2
(5) 2:6 Small, does not meet the ascending condition, so 6 pops up and records the current result as 6*1=6. S={1,1,5},result = 6
2:5 small, does not meet the ascending condition, so 5 pops up and records the current result as 5*2=10 (because the 5,6 that have popped up is ascending). S={1,1},result = 10
2:1 Large, replace the pop-up 5,6 with the 2 re-enter stack. S={1,1,2,2,2},result = 10
(6) 3:2 large, meet the ascending conditions, into the stack. S={1,1,2,2,2,3},result = 10
The stack is built to meet ascending conditions, so you get the above Max (height[i]* (size-i)) =max{3*1, 2*2, 2*3, 2*4, 1*5, 1*6}=8<10, in ascending order of processing.
In summary, result=10
classSolution { Public: intLargestrectanglearea (vector<int> &height) { if(Height.empty ())return 0; intresult =0; Stack<int> s;//elements in stack S is kept in ascending order intIND =0; while(Ind <height.size ()) { if(S.empty () | | height[ind]>=S.top ()) {S.push (height[ind]); } Else { intCount =0;//Pop Count while(!s.empty () && height[ind]<S.top ()) { inttop =S.top (); S.pop (); Count++; Result= Max (result, count*top); } for(inti =0; I <= count; i + +) S.push (Height[ind]); //Push count+1 times} IND++; } //All elements is in the stack s, and in ascending order intCount =0; while(!S.empty ()) {Count++; inttop =S.top (); S.pop (); Result= Max (result, count*top); } returnresult; }};
"Leetcode" largest Rectangle in histogram