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