[LeetCode]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 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 = 10
unit.
For example, Given height = [2,1,5,6,2,3]
, return 10
.
思考:记录每个矩形最左最右比自己高的矩形下标,左右相减即为长,乘以矩形高,即为当前矩形可以组成矩形最大面积。求最大值。
struct Node{ int height; int left; int right; int area; }; class Solution { public: int largestRectangleArea(vector<int> &height) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int i; int maxarea=0; int len=height.size(); Node *h=new Node[len+2]; for(i=1;i<=len;i++) { h[i].height=height[i-1]; h[i].left=i; h[i].right=i; } h[0].height=-1; h[len+1].height=-1; for(i=1;i<=len;i++) { while(h[i].height<=h[h[i].left-1].height) h[i].left=h[h[i].left-1].left; } for(i=len;i>=1;i--) { while(h[i].height<=h[h[i].right+1].height) h[i].right=h[h[i].right+1].right; } for(i=1;i<=len;i++) { h[i].area=h[i].height*(h[i].right-h[i].left+1); if(maxarea<h[i].area) maxarea=h[i].area; } delete []h; return maxarea; } };