美文网首页
[Leetcode] 109. Largest Rectangl

[Leetcode] 109. Largest Rectangl

作者: 时光杂货店 | 来源:发表于2017-03-30 17:41 被阅读9次

题目

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.

238.jpg

For example,
Given heights = [2,1,5,6,2,3],
return 10.

解题之法

class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
        int res = 0;
        for (int i = 0; i < height.size(); ++i) {
            if (i + 1 < height.size() && height[i] <= height[i + 1]) {
                continue;
            }
            int minH = height[i];
            for (int j = i; j >= 0; --j) {
                minH = min(minH, height[j]);
                int area = minH * (i - j + 1);
                res = max(res, area);
            }
        }
        return res;
    }
};

分析

这道题可以用一种巧妙的方法:遍历数组,每找到一个局部峰值,然后向前遍历所有的值,算出共同的矩形面积,每次对比保留最大值。

相关文章

网友评论

      本文标题:[Leetcode] 109. Largest Rectangl

      本文链接:https://www.haomeiwen.com/subject/ebjpottx.html