Largest rectangle in Histogram

Source: Internet
Author: User

GivenNNon-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 =[2,1,5,6,2,3].


The largest rectangle is shown in the shaded area, which has area =10Unit.

For example,

Given Height =[2,1,5,6,2,3],

Return10.

Idea: select the smallest value in the current range each time. Calculated area: Minimum value * Interval Length. Next, divide the current interval into two subintervals, and then process the subintervals in the same way. This method is very complicated to implement.

Stack operations can be used to solve the problem more concisely. Traverse the input data in sequence. If the current element is greater than the top element of the stack, the data is written to the stack. Otherwise, the top element of the stack goes out of the stack and the maximum area of the rectangle where the top element of the stack is located is calculated. This allows us to determine at the same time the position of the elements on the top left and right sides of the stack with a smaller value and closest value. The following code is very concise on the Internet. By adding 0 to the end of the input array, all elements will be pushed out of the stack to get the correct result:

 1 class Solution { 2 public: 3     int largestRectangleArea( vector<int> &height ) { 4         height.push_back( 0 ); 5         stack<int> stk; 6         int i = 0, maxArea = 0; 7         while(i < height.size()){ 8             if( stk.empty() || height[stk.top()] <= height[i] ){ 9                 stk.push(i++);10             }else {11                 int t = stk.top();12                 stk.pop();13                 maxArea = max( maxArea, height[t] * ( stk.empty() ? i : i-stk.top()-1 ) );14             }15         }16         return maxArea;17     }18 };

 

Largest rectangle in Histogram

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.