Find the rectangle with the largest area in the histogram (c)

Source: Internet
Author: User

Note: I implemented it cyclically. It is definitely not the optimal algorithm. Please leave a message to discuss it. (The question is from Pang go.com)

Question details:

Given a histogram, the height of each small block is determined by N non-negative integers, and the width of each small block is 1. Find the rectangle with the largest area in the histogram.


As shown in, the width of each part in the histogram is 1, and the given height of each part is [2, 1, 5, 6, 2, 3]:



<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Authorization + CjxwPgogICDEx8O0yc/authorization + authorization/nKvrXE0vXTsLK/t9a1xMPmu/2 jrMPmu/authorization + CjxwPgo8YnI + signature + Signature = "http://www.bkjia.com/uploadfile/Collfiles/20131220/20131220132908209.png" alt = "\">


Complete the largestRectangleArea function to find the rectangle with the largest area in the histogram. For example, if the height of each small part of the histogram is [2, 1, 5, 6, 2, 3], 10 is returned.

Solution code:
int minElement(const int *h, int b, int e){    int min = h[b++];    for (; b < e; ++b)    {        if (h[b] < min)            min = h[b];    }    return min;}int largestRectangleArea(const int *height,int n) {    int max = 0;    int min = 0;    int i, j;    for (i = 0; i < n; ++i)    {        for (j = i; j < n; ++j)        {            min = minElement(height, i, j + 1);            if ((j+1-i)*min > max)            {                max = (j+1-i)*min;            }        }    }    return max;}



Related Article

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.