【LeetCode】Largest Rectangle in Histogram
2014-05-27 00:03
274 查看
题目描述:
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 =
The largest rectangle is shown in the shaded area, which has area =
For example,
Given height =
return
这题目O(n*n)的解法太明显,试都不用试就知道肯定TLE……但是更效率的算法一直想不出来。只好求助于万能的网络,看到大神的解法,真是觉得跟自己不是一个世界的人……什么时候能达到这种水平……
思路是这样的:
对位置为i的元素,能构成的最大矩形:以i为中心向两边延伸,左边界为第一个小于i的数,右边界为第一个小于i的数。如何确定这个位置,从思路上来讲挺困难的。
画图无能,引用下详细解释的外链: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.
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 =
10unit.
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 * i; else n = height * (i - h.top() - 1); res = std::max(res, n); } } return res; } };
相关文章推荐
- [LeetCode] Largest Rectangle in Histogram
- [LeetCode] Largest Rectangle in Histogram 解题报告
- LeetCode —— Largest Rectangle in Histogram
- LeetCode: Largest Rectangle in Histogram(直方图最大面积)
- LeetCode-Largest Rectangle in Histogram
- [LeetCode] Largest Rectangle in Histogram
- leetcode-084:Largest Rectangle in Histogram
- LeetCode 笔记系列 17 Largest Rectangle in Histogram
- [LeetCode] Largest Rectangle in Histogram、Maximal Rectangle
- [leetcode]Largest Rectangle in Histogram
- [Leetcode] Largest Rectangle in Histogram
- LeetCode: Largest Rectangle in Histogram
- [leetcode] Largest Rectangle in Histogram
- [leetcode]Largest Rectangle in Histogram
- LeetCode: Largest Rectangle in Histogram(直方图最大面积)
- leetcode之Largest Rectangle in Histogram
- [Leetcode] Largest Rectangle in Histogram
- leetcode - Largest Rectangle in Histogram
- leetcode -- Largest Rectangle in Histogram TODO O(N)
- LeetCode Online Judge 题目C# 练习 - Largest Rectangle in Histogram