Leetcode Note: Largest Rectangle in Histogram
I. Description
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 where width of each bar is 1, given height = [,].
VcPmu/memory + memory/memory + Memory + GzrMqxoaM8L3A + DQo8cD7V/memory + Memory + memory/memory + DQo8cD48aW1nIGFsdD0 = "here write picture description" src = "http://www.bkjia.com/uploads/allimg/151016/042959DN-2.png" title = "\" />
In the figure,height = [5,6,7,8,3]
The feature is that except the last one, the front is all incremental, and the height of the last column is smaller than the height of all the front columns.
We know that except the last column, the height from the first column to the last column is rising. If one column is used as the height of the rectangle, the width of the rectangle that can be obtained in sequence can be calculated directly: Use5
The first four columns can be used as the height.4*5
The height of the rectangle.6
Can be composed of Columns3*6
The rectangle ...... Therefore, only one traversal is required.height
To calculate the maximum area, that is, the time complexity.O(n)
.
Refer to the blog post to refer to the column chart with this feature as the "peak Chart ".
The following describes the specific steps of the algorithm:
1. Inheight
Add at the end of the array0
To obtain a histogram that complies with the preceding rules.
2. Define a stack k to traverse the Arrayheight
, Ifheight[index]
Greaterstack.top()
, Into the stack; otherwise, it is out of the stack until the top element of the stack is smallerheight[index]
. Since the height of these elements is increasing, we can find the rectangular area enclosed in these columns in sequence and update its maximum value.
3. Repeat the above process until the element with the last 0 value is traversed. All the elements in the stack will pop up and calculate the last area, and the maximum area will be returned.
Note that what is stored in the stack is notheight
Element size,height
The benefit of doing so is that the calculation of the width will not be affected. The index value of the current traversal-the index value on the top of the current stack-1 = the width of the current rectangle.
Iii. Sample Code
Class Solution {public: int largestRectangleArea (vector
& Height) {if (height. size () = 0) return 0; height. push_back (0); int MaxHist = 0; // store the largest rectangular area stack
K; // use the stack to store the height index for (int index = 0; index
Iv. Summary
This topic requires traversing each column and regard it as the height of the rectangle to find the maximum area of the rectangle in the histogram, but it uses the stack cleverly, the entire height is converted into a group of "wave top graphs" to solve the problem. It makes O (n) time complex and deserves further study!