# [LeetCode] 84. Largest Rectangle in Histogram 柱状图中最大的矩形

Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.

Example 1:

Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.


Example 2:

Input: heights = [2,4]
Output: 4

Constraints:

• 1 <= heights.length <= 10^5
• 0 <= heights[i] <= 10^4

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

class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int res = 0;
stack<int> st;
heights.push_back(0);
for (int i = 0; i < heights.size(); ++i) {
if (st.empty() || heights[st.top()] < heights[i]) {
st.push(i);
} else {
int cur = st.top(); st.pop();
res = max(res, heights[cur] * (st.empty() ? i : (i - st.top() - 1)));
--i;
}
}
return res;
}
};

class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int res = 0;
stack<int> st;
heights.push_back(0);
for (int i = 0; i < heights.size(); ++i) {
while (!st.empty() && heights[st.top()] >= heights[i]) {
int cur = st.top(); st.pop();
res = max(res, heights[cur] * (st.empty() ? i : (i - st.top() - 1)));
}
st.push(i);
}
return res;
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/84

Maximal Square

Maximal Rectangle

Maximum Score of a Good Subarray

https://leetcode.com/problems/largest-rectangle-in-histogram/

https://leetcode.com/problems/largest-rectangle-in-histogram/discuss/28905/My-concise-C%2B%2B-solution-AC-90-ms

https://leetcode.com/problems/largest-rectangle-in-histogram/discuss/28902/5ms-O(n)-Java-solution-explained-(beats-96)

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2015-03-09 02:38  Grandyang  阅读(49271)  评论(15编辑  收藏  举报