c++]leetcode:133 largest Rectangle in histogram (maximum rectangular area)

Source: Internet
Author: User

Title:

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 .

Anwser 1:brute Force

idea: the poor lifting method, for each bar of the histogram, we are poor to lift all the left border, the largest area of the record down. The time complexity is O (n^2). But the simple method of poor lifting in Leetcode will be tle. All we need are some pruning methods, such as finding the right border. We find that when Height[k] >= height[k-1], no matter what the left boundary value, select Height[k] as the right boundary will always be larger than the area formed by the selection of height[k-1]. So, when we select the right boundary, we first find a K of height[k] < height[k-1], then take k-1 as the right boundary, skip the middle bar, and then go all the way to the left to find the maximum area.

The method of poor lifting also has a way of thinking, that is, the current bar is a rectangular height, and then left and right two pointers to the array to move to each side, until the height is lower than the current bar height cutoff, and then with the current bar height multiplied by the width of both sides is the maximum area. Because we have calculated the maximum matrix of our own target height for all bars, the best results will definitely be taken. But again, it is time-out without pruning.

Attention:

1. In the case of a poor lift, we need to maintain a minimum height from the current K forward.

int lowest = Height[i];            for (int j = i; j >= 0; j--)            {                lowest = min (height[j], lowest);
2. Attention to pruning methods

for (int k = i + 1; k < height.size (); k++)            {                if (Height[k] < height[k-1])                {                    i = k-1;                    break;                }                else                {                    i = k;                }            }

AC Code:

Class Solution {public:    int Largestrectanglearea (vector<int> &height) {        int maxarea = 0;                for (int i = 0; i < height.size (), i++)        {for            (int k = i + 1; k < height.size (); k++)            {                if (Height[k] & Lt Height[k-1])                {                    i = k-1;                    break;                }                else                {                    i = k;                }            }                        int lowest = Height[i];            for (int j = i; j >= 0; j--)            {                lowest = min (height[j], lowest);                int Curarea = lowest * (i-j + 1);                Maxarea = Max (Maxarea, Curarea);            }        }        return maxarea;}    ;

Answer 2: Stack optimization algorithm

idea: We maintain a stack, the stack from the low-up height is incremented, if encountered the current bar is lower than the top element of the stack, then out of the stack until the condition is satisfied, in this process, we constantly put the stack top element of the stack as the lowest height to calculate the maximum area. The key issue is how to determine the maximum range of heights that the stack element corresponds to when it is out of the stack. If the stack is empty, then all elements so far (except the current subscript element) are greater than the stack element height (otherwise there will be elements in the stack), then the matrix area is the stack top element height h[t] * current subscript i. If the stack is not empty, then it is from the top element of the current stack before the next to the current subscript element is greater than the height of the stack element, because the current stack top element is the first one smaller than the stack element. Specifically, you can look at this picture:

Another detail to note is the calculation of the area during the stack.

H[T] * (Stack.isempty ()? I:i-Stack.peek ()-1)

H[t] is the top element of the stack that just popped up. The area calculated at this time is h[t] and the largest area in front of "Upper society" can be enclosed. This time to pay attention to, oh, the stack index points to the elements are smaller than h[t], if H[T] is currently the smallest, then the stack is empty oh. Between the top elements of the stack and the h[t] (excluding the h[t] and top elements), they are both larger.

What we need to note is that the rest of the stack should be emptied and judged at the end, because the algorithm determines the area of the front element each time, and if there are still elements inside the stack after the loop is over, continue to maintain the area until the stack is empty.

AC Code:

Class Solution {public:    int Largestrectanglearea (vector<int> &height) {                stack<int> Stk;        int maxarea = 0;        int TP;   Stack top element        int area_with_tp;  Store the top element of the stack as the area of the shortest plate                int i = 0;        while (I < height.size ())        {            if (stk.empty () | | height[i] >= height[stk.top ()])                Stk.push (i++);            else            {                TP = Stk.top ();                Stk.pop ();                AREA_WITH_TP = height[tp] * (Stk.empty ()? I:i-Stk.top ()-1);                Maxarea = Max (Maxarea, AREA_WITH_TP);            }        }                If the stack is still non-empty continue processing        while (!stk.empty ())        {            tp = Stk.top ();            Stk.pop ();            AREA_WITH_TP = height[tp] * (Stk.empty ()? I:i-Stk.top ()-1);            Maxarea = Max (Maxarea, AREA_WITH_TP);        }        return maxarea;}    ;

This problem has two blog posts that can help understand.

Largest Rectangle in histogramlargest rectangular area in a histogram | Set 2This problem is more around, it is difficult to understand, need to think carefully. The optimization method only needs to be scanned once, the time complexity is O (n), the space complexity is the size of the stack, the worst is O (n).

This problem also has an extension topic maximal Rectangle, using this problem as a sub-program, is a more complex topic.

c++]leetcode:133 largest Rectangle in histogram (maximum rectangular area)

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.