Maximum rectangular area of an array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.