[leetcode] Largest Rectangle in Histogram

来源:互联网 发布:淘宝房产司法拍卖 编辑:程序博客网 时间:2024/06/10 04:51
Largest Rectangle in HistogramApr 23 '12

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.

这道题与Maximal Rectangle点击打开链接有些相似,不过要简单些,这里只有一维,而Maximal Rectangle是两维。思路相同,是对第i个小矩形块往前找,往前合并一个小矩形块要计算高与宽,宽就是小矩形块的个数,高就是几个小矩形块中长度最小的那个值

class Solution {public:    int largestRectangleArea(vector<int> &height) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int area=0;        int len=height.size();        if(len==0) return 0;        for(int i=0; i<len; i++)        {            int h=INT_MAX;            for(int j=i; j>=0; j--)            {                   h=std::min(h, height[j]);                area=std::max(area, h*(i-j+1));            }        }        return area;    }};

原创粉丝点击