Given n non-negative integers representing the histogram's bar height where the width of each bar are 1, find the area of L Argest 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 = ten unit.
For example,
Given Heights = [2,1,5,6,2,3],
Return 10.
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
Public classSolution { Public Static int Largestrectanglearea(int[] heights) {stack<integer> Mstack =NewStack<integer> ();intCountintresult =0; for(inti =0; i < heights.length; i++) {if(Mstack.isempty () | | Mstack.peek () <= heights[i]) {Mstack.push (heights[i]); }Else{count =1; while(!mstack.isempty () && mstack.peek () > Heights[i]) {result = max (result, Mstack.peek () * count); Mstack.pop (); count++; } while(Count >1) {Mstack.push (heights[i]); count--; } mstack.push (Heights[i]); } }intnum =1; while(!mstack.isempty ()) {result = max (result, mstack.pop () * num); num++; }returnResult } Public Static int Max(intIintj) {returnI >= j? I:j; }}
Leetcode 14 84. Largest Rectangle in histogram (hard)