Given
NNon-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],
Return
10. For more information, see http://www.geeksforgeeks.org/largest-rectangle-under-histogram/, as shown in the following code.
int largestRectangleArea(vector<int> &height) { int maxarea = 0, index = 0, n = height.size(); stack<int> s; while(index < n){ if(s.empty() || height[s.top()] <= height[index]) s.push(index++); else{ int topIndex = s.top();s.pop(); int topOfArea = height[topIndex]*(s.empty() ? index : index-s.top()-1); maxarea = max(topOfArea,maxarea); } } while(!s.empty()){ int topIndex = s.top();s.pop(); int topOfArea = height[topIndex]*(s.empty() ? index : index-s.top()-1); maxarea = max(topOfArea,maxarea); } return maxarea; }View code's own idea about this question connects the highest point of the histogram to form a curve similar to a trough. The two valleys are a partial convex shape (a partial histogram) different pods have their own maximum histogram areas, which do not affect each other (except the bottom trough and trough). The area of each bulge is obtained. The maximum value is obtained and the line between the bottom trough forms a curve, find the raised area until there is no raised at the end. The biggest area is the histogram area.