LeetCode 84. Largest Rectangle in Histogram

来源:互联网 发布:淘宝购买小号 编辑:程序博客网 时间:2024/04/27 22:52

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

return 10.

       求组成矩形最大面积。矩形面积等于长乘以宽。如果我们在求面积的时候两者都变,那将是十分复杂的事情。我们在做题的时候需要固定一个,我们以直方图的一条来说,我们固定其高度,算得能以当前高度能够向左和向右扩展多少。那么我们的重点就变成了需要计算每一条直方图上能向左和向右扩展到的位置,即如下代码中的left和rigth数组。代码如下:

class Solution {public:    int largestRectangleArea(vector<int>& heights) {        int n=heights.size();        if(n<=0)        return 0;        int left[n];        left[0]=0;        for(int i=1;i<n;i++)        {           int A=i;           while(A>0&&(heights[A-1]>=heights[i]))           A=left[A-1];           left[i]=A;        }        int right[n];        right[n-1]=n-1;        for(int i=n-2;i>=0;i--)        {           int A=i;           while(A<n-1&&heights[A+1]>=heights[i])           A=right[A+1];           right[i]=A;        }        int ans=0;        for(int i=0;i<n;i++)        {            ans=max(ans,(right[i]-left[i]+1)*heights[i]);        }        return ans;    }};
       这题我觉得是思考问题的一种方式吧,矩形的面积=长成宽。固定长,扩展宽。最终循环遍历求得最大值。

0 0
原创粉丝点击