Largest Rectangle in Histogram
2017-05-21 19:12
169 查看
Largest Rectangle in Histogram
标签(空格分隔): leetcode, 算法,堆栈1. 题目
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 heights = [2,1,5,6,2,3],
return 10.
2. 解答
解法一:暴力法
对柱状图的每一项,向前向后比较找出它能行程的面积最大的矩形。class Solution { public: int largestRectangleArea(vector<int>& heights) { if (heights.empty()) { return 0; } int maxArea = heights[0]; for (int i = 0; i < heights.size(); ++i) { int area = heights[i]; //柱状图中的每一项能形成的最大面积 for (int j = i + 1; j < heights.size(); ++j) { if (heights[j] >= heights[i]) { area += heights[i]; } else { break; } } for (int k = i - 1; k >= 0; --k) { if (heights[k] >= heights[i]) { area += heights[i]; } else { break; } } if (area > maxArea) { maxArea = area; } } return maxArea; } };
然而由于超时无法通过o(n^2)。
解法二:利用栈
利用栈构造非递减序列, 参考博客。class Solution { public: int largestRectangleArea(vector<int>& heights) { int maxArea = 0; stack<int> s; for (vector<int>::size_type i = 0; i < heights.size(); ++i) { if (s.empty() || s.top() <= heights[i]) { s.push(heights[i]); } else { int popCnt = 0; while (!s.empty() && s.top() > heights[i]) { maxArea = max(maxArea, s.top() * (popCnt + 1)); s.pop(); ++popCnt; } while(popCnt) { s.push(heights[i]); --popCnt; } s.push(heights[i]); } } int popCnt = 0; while (!s.empty()) { maxArea = max(maxArea, s.top() * (popCnt + 1)); s.pop(); ++popCnt; } return maxArea; } };
相关文章推荐
- POJ-2559-Largest Rectangle in a Histogram-单调栈
- hdu 1506 Largest Rectangle in a Histogram(求最大的矩形)
- [HDU 1506 Largest Rectangle in a Histogram] ...类dp?...
- LEETCODE: Largest Rectangle in Histogram
- Largest Rectangle in Histogram, 求矩形图中最大的长方形面积
- Largest Rectangle in Histogram
- [leetcode 84] Largest Rectangle in Histogram
- Largest Rectangle in Histogram
- LeetCode Largest Rectangle in Histogram
- POJ 2559 Largest Rectangle in a Histogram 单调栈(STL版)
- [LeetCode 84, 85]Largest Rectangle in Histogram / Maximal Rectangle
- Java for LeetCode 084 Largest Rectangle in Histogram【HARD】
- leetcode.84. Largest Rectangle in Histogram
- poj2559 Largest Rectangle in a Histogram 栈
- HDU-1506 Largest Rectangle in a Histogram 动态规划
- hdu 1506 Largest Rectangle in a Histogram(dp)
- 【poj2559】Largest Rectangle in a Histogram
- HDU1506 Largest Rectangle in a Histogram
- zoj 1985 - Largest Rectangle in a Histogram
- 84. Largest Rectangle in Histogram