Problem Description :
Given an array of arr, where Arr[i] represents a rectangle with a base of 1 and a height of arr[i], the array arr can represent a bar chart.
Here, the rectangle with the largest area of the rectangle contained in the histogram is obtained.
For example: int arr[] = {2, 4, 7, 3, 5, 4, 6, 9, 4};
The array can represent the following bar chart:
In this histogram, the area of the largest rectangle is 8 * 3 = 24;
The code is as follows :
/** @brief * The largest rectangle in the column chart represented by the array * * @param arr[] int * @param len int * @return int **/intMaxarea (intArr[],intLen) {Stack<int> idxstack;//store subscript, the corresponding element is strictly increased order intRET =0;//return Results intIDX =0;//Current Element subscript intPre =0;//Farthest position of the current element to the left for(inti =0; i < Len; ++i) {if(Idxstack.empty () | | arr[idxstack.top ()] <Arr[i]) {Idxstack.push (i); } Else //out of the stack { while(!idxstack.empty () && arr[idxstack.top ()] >=Arr[i]) {idx=Idxstack.top (); Idxstack.pop (); /**< for Element Arr[idx], extended to left and right ends [pre, I]*/Pre= Idxstack.empty ()?0: Idxstack.top () +1; RET= Max (ret, (i-pre) *Arr[idx]); } idxstack.push (i); //right border into the stack } } /**< If the stack still contains elements, the range is assumed to be [Pre, Len]. All out of the stack at this time*/ while(!Idxstack.empty ()) {idx=Idxstack.top (); Idxstack.pop (); Pre= Idxstack.empty ()?0: Idxstack.top () +1; RET= Max (ret, (len-pre) *Arr[idx]); } returnret;}
Maximum rectangular area of an array