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
.
Given a set of non-negative numbers, and then find the maximum area (drawn on the axis, the width is 1).
The problem is still relatively difficult, I did not do it anyway.
At first I was thinking of a more violent algorithm, that is, to traverse each number, and then take this number as the center, extending to both sides to find the largest area (the smallest is also himself). But it's timed out.
Public classSolution { Public intLargestrectanglearea (int[] Heights) { intLen =heights.length; intHigh, result = 0, ans; int[] flag =New int[Len]; for(inti = 0;i<len;i++){ if(Flag[i] = = 1) Continue; High=Heights[i]; Ans=High ; intj = i+1; while(j<Len) { if(Heights[j] >High ) {ans+=High ; }Else if(Heights[j] = =High ) {ans+=High ; FLAG[J]= 1; } Else Break; J++; } J= I-1; while(J >= 0){ if(Heights[j] >=High ) {ans+=High ; } Else Break; J--; } result= Result>ans?Result:ans; } returnresult; }}
And then think of the use of dynamic planning, but the code has been a problem, and did not pass.
Later read the answer, found also similar to the idea of dynamic planning, the use of very ingenious, find the left and right border, and then successfully found.
Public classSolution { Public intLargestrectanglearea (int[] Heights) { intLen =heights.length; intresult = 0; if(len = = 0) return0; int[] left =New int[Len]; int[] right =New int[Len]; left[0] = 0; for(inti = 1;i<len;i++){ intCurleft = i-1; while(curleft >= 0 && heights[curleft]>=Heights[i]) {Curleft= Left[curleft]-1; } Left[i]= Curleft+1; } Right[len-1] = len-1; for(inti = len-2;i>=0;i--){ intCurright = i+1; while(Curright<len && heights[curright]>=Heights[i]) Curright= Right[curright]+1; Right[i]= CurRight-1; } for(inti = 0;i<len;i++) {result= Math.max (result, (right[i]-left[i]+1) *(Heights[i])); } returnresult; }}
Leetcode largest Rectangle in histogram-----java