【LeetCode】Largest Rectangle in Histogram

来源:互联网 发布:淘宝退货率太高 编辑:程序博客网 时间:2024/05/29 14:56

题目描述:

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.

这题目O(n*n)的解法太明显,试都不用试就知道肯定TLE……但是更效率的算法一直想不出来。只好求助于万能的网络,看到大神的解法,真是觉得跟自己不是一个世界的人……什么时候能达到这种水平……

思路是这样的:

对位置为i的元素,能构成的最大矩形:以i为中心向两边延伸,左边界为第一个小于i的数,右边界为第一个小于i的数。如何确定这个位置,从思路上来讲挺困难的。

画图无能,引用下详细解释的外链:Largest Rectangle in Histogram

代码如下:

class Solution {public:int largestRectangleArea(vector<int> &height) {stack<int> h;int res(0);height.push_back(0);int i = 0;while (i < height.size()){if (h.empty() || height[i] >= height[h.top()])h.push(i++);else{int n = h.top();h.pop();if (h.empty())n = height[n] * i;elsen = height[n] * (i - h.top() - 1);res = std::max(res, n);}}return res;}};


0 0
原创粉丝点击