Topic:
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 Heights = [2,1,5,6,2,3] ,
Return 10 .
test instructions and analysis: A series of adjacent histograms are given to find out the maximum area that can be composed.
Method One: Brute force solution, find the two number of sub-arrays to find, as the leftmost and the most right side, and then find the lowest of the straight side, get the area, such an array altogether has 2^n, find the lowest straight square is O (n), so the time complexity of O (n^3), will time out, slightly
Method Two: You can go from each straight side to the two sides, with their own height as standard, until the two sides below their own height, and then use their own height multiplied by the width of both sides to get the matrix area. Because the maximum matrix of the target height is calculated for any bar, the best results are definitely taken. Each side of the complexity is O (n), a total of n bar, so the time complexity is O (n^2), will also time out ...
Method Three: if the height array is known to be ascending, what should be done? For example 1,2,5,7,8 (1*5) vs. (2*4) vs. (5*3) vs. (7*2) vs. (8*1) is Max (height[i]*), and the purpose of using stacks is to construct such ascending sequences, which are solved by the above method. Save the maximum possible value when constructing the stack
Code:
classSolution { Public intLargestrectanglearea (int[] Heights) { if(Heights = =NULL|| Heights.length==0) return0; intTempresult = 0; Stack<Integer> stack =NewStack<>(); Stack.push (heights[0]); for(inti=1;i){ if(Heights[i]>=stack.peek ()) {//AscendingStack.push (Heights[i]); }Else{ if(!Stack.isempty ()) { intCount = 0; intMin =Stack.peek (); while(!stack.isempty () && Stack.peek () >Heights[i]) { if(Stack.peek () <min) {min=Stack.peek (); } stack.pop (); Count++; if(tempresult<count*min) {Tempresult= count*min; } } intJ=0; while(j<=count) {Stack.push (heights[i]); J++; } } } } for(inti=heights.length-1;i>=0;i--){ intx=Stack.pop (); if((heights.length-i) *x>Tempresult) {Tempresult= (heights.length-i) *x; } } returnTempresult; }}
[Leetcode] 84. Largest Rectangle in histogram Java