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 .
Reference: http://blog.csdn.net/abcbc/article/details/8943485
C + + Implementation code:
#include <iostream>#include<vector>#include<stack>using namespacestd;classsolution{ Public: intLargestrectanglearea (vector<int> &height) { if(Height.empty ())return 0; intMaxarea=0; intI=0; intn=height.size (); Stack<int>St; intstart; for(i=0; i<n;i++) { if(St.empty () | | Height[i]>height[st.top ()]) St.push (i); Else{Start=St.top (); St.pop ();
Note that the index of the top element of the previous stack is subtracted from the current element when the width is calculatedintWidth=st.empty ()? I:i-st.top ()-1; Maxarea=max (width*Height[start],maxarea); I--;//processing to a stack is empty or the elements in the stack are smaller than the currently processed elements } } while(!St.empty ()) {Start=St.top (); St.pop (); intWidth=st.empty ()? N:n-st.top ()-1; Maxarea=max (width*Height[start],maxarea); } returnMaxarea; }};intMain () {solution S; Vector<int> height={1,2,2}; cout<<s.largestrectanglearea (height) <<Endl;}
I wrote an O (n^2) timed out.
#include <iostream>#include<vector>#include<climits>using namespacestd;classSolution { Public: intLargestrectanglearea (vector<int> &height) { if(Height.empty ())return 0; inti,j; intMinH; intMaxarea=0; intn=height.size (); for(i=0; i<n;i++) {MinH=Height[i]; for(j=i;j<n;j++) {MinH=min (minh,height[j]); Maxarea=max (maxarea,minh* (j-i+1)); } } returnMaxarea; }};intMain () {solution S; Vector<int> height={2,1,5,6,2,3}; cout<<s.largestrectanglearea (height) <<Endl;}
Largest Rectangle in histogram