(Daily algorithm) Leetcode--largest Rectangle in histogram (maximum solid rectangle)

Source: Internet
Author: User

Train of thought: if the time complexity requirement is O (n 2 ), the solution is more and better understanding. For example, you can traverse the column at the current I position, calculate the maximum rectangle ending with this I column, and then find the total maximum rectangle.

Given n non-negative integers representing the histogram ' s bar height where the width of each bar is 1, find th E 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 = unit.

For example,
Given height = [2,1,5,6,2,3] ,
return.


Calculating the maximum rectangle ending with the I column requires a single traversal, so the time complexity is O (n 2 ).

Or you can use another method: the height of the maximum rectangle is undoubtedly equal to the height of a column, or the maximum rectangle necessarily contains all of a column.

Therefore, you can traverse all the columns, to the current column I, with its height around the expansion, to see the height of the current column I can contain up to how large rectangular area. Finally, the largest total area can be selected. The code for this idea is as follows:

classSolution { Public:  intLargestrectanglearea ( vector<int>&height) {    if(height.size () = =0)return 0;     intMax =0;      for(inti =0; I < height.size (); ++i) {      intMID =i;       intArea =0;        for(; Mid >=0&& Height[mid] >= height[i]; Area + = Height[i],--mid);        for(Mid = i+1; Mid < Height.size () && Height[mid] >= height[i]; Area + = Height[i], + +mid);       if(Max < area) Max =Area ;     }    returnMax;   }};

It's not an accident, it's not a big set test.

But the reason to introduce this idea is because this idea can hatch out the time complexity of O (n) solution.

This solution is ingenious, not my original.

First, let's take a look at the following example:

The height of the content is [5,6,7,8,3], except the last one, the front all keep incrementing, and the height of the last column is less than all the previous column height.

For this feature of the histogram, if using the above-mentioned "each use the height of each histogram as the height of the rectangle, to calculate the area" method, also need to use nested loops?

We know that in addition to the last one, from the first to the penultimate column height is rising, then if you use each column height as the height of the rectangle, then you can get the width of the rectangle can be directly calculated: Using 5 as a height can use the first four columns to form a 4*5 rectangle, height 6 can be composed of the 6 Rectangle ... So just traverse once to select the maximum area.

For this type of bar chart, the time complexity of the maximum rectangular area is O (n).

We refer to the histogram of this feature as the crest chart.

The following steps describe the new solution:

(1) Add a 0 to the height tail, which is a column of 0. The effect is in the end can also make up the kind of "crest map" mentioned above.

(2) A stack is defined and then traversed if height[i] is greater than stack.top (), and the stack is entered. Conversely, the stack is out until the top element is less than height[i].

Since these elements of the stack are ascending in height, we can find out the largest rectangles in these columns. Even better, since the columns that are ejected are above the "crest" (such as popping I to i+k, then all of these columns are taller than the height of i-1 and i+k+1), so if we use the thought solution of the "left and right extension looking column" before, with the height of these columns as the height of the entire rectangle, The left and right stretches of the rectangle contain columns that do not exceed this "crest" because the column heights outside the crest are lower than theirs. "Crest Map" is actually the "island" to solve the largest rectangle, it does not interfere with the outside.

(3) because the elements larger than height[i] are out, height[i] is larger than the top element of the stack, so again into the stack. This is repeated until the last bar with the height of 0 is traversed, triggering the last pop-up and the last area calculation, after which the stack is empty.

(4) Returns the maximum area value.

The code below, which is not the height of the stack, but the index of height, the advantage of doing so does not affect the width of the calculation. Code from water fish-[leetcode] largest Rectangle in histogram problem solving report

1:intLargestrectanglearea ( vector<int>&h) {2: Stack<int>S; 3: H.push_back (0); 4:intsum =0; 5: for(inti =0; I < h.size (); i++) {  6:if(S.empty () | | h[i] >h[s.top ()])  S.push (i); 7:Else {  8:intTMP =S.top (); 9: S.pop (); Ten: sum = max (sum, h[tmp]* (S.empty ()? I:i-s.top ()-1));  One: i--;  A:            }   -:       }   -:returnsum;  the:  }

The biggest highlight of this solution is

(1) The stack is index, the width of the calculation area using the difference of index, so although the stack pops up the column, but does not affect the width of the calculation, can still calculate the area.

(2) The solution essentially is to look at each column as a rectangular height to find the maximum area, but it by the stack, the whole height into a set of "crest map" to solve, this height layout, the maximum area of the calculation is O (n), and then the maximum area of all the peaks to take the maximum value. Finally, the time complexity of O (n) was achieved to cover all the columns.

What a wonderful solution!

(Daily algorithm) Leetcode--largest Rectangle in histogram (maximum solid rectangle)

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.