delete代码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.

    delete和代码

    Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

    delete和代码

    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.

    分析:利用动态规划的思惟。先定义两个两个数组 l[i] ,r[i]分别表示height[i]双方第一个小于height[i]之前的数的位置。

    

这样,以height[i]为高,最大的矩形面积就是 (r[i]-l[i]+1)*height[i]。

    


    

转移方程为:当height[l[i]-1]>height[i], l[i]=l[l[i]-1]。
    每日一道理
那蝴蝶花依然花开花落,而我心中的蝴蝶早已化作雄鹰飞向了广阔的蓝天。

    

                        当height[r[i]+1]>height[i], r[i]=r[r[i]+1]。

    代码如下:

        int largestRectangleArea(vector<int> &height) {
        int n=height.size();
        int *l=new int [n];
        int *r=new int [n];
        for(int i=0;i<n;i++)
        {
            l[i]=i;
            while(l[i]>0&&height[l[i]-1]>=height[i])
            {
                l[i]=l[l[i]-1];
            }
        }
        for(int i=n-1;i>=0;i--)
        {
            r[i]=i;
            while(r[i]<n-1&&height[r[i]+1]>=height[i])
            {
                r[i]=r[r[i]+1];
            }
        }
        int result=0;
        for(int i=0;i<n;i++)
        {
            if((r[i]-l[i]+1)*height[i]>result)
            {
                result=(r[i]-l[i]+1)*height[i];
            }
        }
        delete []l;
        delete []r;
        return result;
    }

文章结束给大家分享下程序员的一些笑话语录: 人脑与电脑的相同点和不同点,人脑会记忆数字,电脑也会记忆数字;人脑会记忆程序,电脑也会记忆程序,但是人脑具有感知能力,这种能力电脑无法模仿,人的记忆会影响到人做任何事情,但是电脑只有程序软件。比尔还表示,人脑与电脑之间最重要的一个差别就是潜意识。对于人脑存储记忆的特别之处,比尔表示,人脑并不大,但是人脑重要的功能是联络,人脑会把同样的记忆存储在不同的地方,因此记忆读取的速度就不相同,而这种速度取决于使用的频率和知识的重要性。人脑的记忆存储能力会随着年龄增长而退化,同时记忆的质量也会随着年龄退化。经典语录网

--------------------------------- 原创文章 By
delete和代码
---------------------------------

posted @ 2013-05-26 23:44  xinyuyuanm  阅读(146)  评论(0编辑  收藏  举报