Largest Rectangle in histogram
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 .
The general practice is to calculate the maximum area value for each point, and finally get the overall maximum, and the time complexity is O (n^2).
Using the nature of the stack, you can reduce the complexity of time to O (n). Refer to this blog post.
1 classSolution {2 Public:3 intLargestrectanglearea (vector<int>&height) {4 intresult=0;5Height.push_back (0);6stack<int>Mystack;7 for(intI=0; I)8 {9 if(Mystack.empty () | | height[mystack.top ()]<=Height[i])Ten { One Mystack.push (i); A } - Else - { the intindex =mystack.top (); - Mystack.pop (); - intArea = height[index]* (Mystack.empty ()? I: (I-mystack.top ()-1)); -result =Max (Result,area); +i--; - } + } A returnresult; at } -};
[Leetcode]largest Rectangle in histogram