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: height = [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.
Related Topics
- Array
- Stack
Similar Questions
No. | Title | Difficulty |
---|---|---|
11 | Container With Most Water | ☆☆☆ |
42 | Trapping Rain Water | ☆☆☆ |
85 | Maximal Rectangle | ☆☆☆☆ |
Solution
Approach 1: Brute Force
以该点的高度为中心,左右探测。
时间超时。
class Solution {
public:
int largestRectangleArea(vector<int>& height) {
int res = 0;
int n = height.size();
if (n <= 0) return 0;
for (int i = 0; i < n; i++) {
int H = height[i];
int L = i;
int R = i;
while (L >= 0 && height[L] >= H) L--;
while (R < n && height[R] >= H) R++;
res = max(res, H*(R-L-1));
}
return res;
}
};
Approach 2: Using Stack
用栈跟踪左边界。
中间夹着的永远是凸型。
入栈出栈动画及面积计算过程见文末。
class Solution {
public:
int largestRectangleArea(vector<int>& hist) {
int n = hist.size();
// Create an empty stack. The stack holds indexes
// of hist[] array. The bars stored in stack are
// always in increasing order of their heights.
stack<int> s;
int max_area = 0; // Initialize max area
int tp; // To store top of stack
int area_with_top; // To store area with top bar
// as the smallest bar
// Run through all bars of given histogram
int i = 0;
while (i < n) {
// If this bar is higher than the bar on top
// stack, push it to stack
if (s.empty() || hist[i] > hist[s.top()]) {
s.push(i++);
// If this bar is lower than top of stack,
// then calculate area of rectangle with stack
// top as the smallest (or minimum height) bar.
// 'i' is 'right index' for the top and element
// before top in stack is 'left index'
} else {
tp = s.top(); // store the top index
s.pop(); // pop the top
// Calculate the area with hist[tp] stack
// as smallest bar
area_with_top = hist[tp] * (s.empty() ? i : i - s.top() - 1);
// update max area, if needed
max_area = max(max_area, area_with_top);
}
}
// Now pop the remaining bars from stack and calculate
// area with every popped bar as the smallest bar
while (s.empty() == false) {
tp = s.top();
s.pop();
area_with_top = hist[tp] * (s.empty() ? i : i - s.top() - 1);
max_area = max(max_area, area_with_top);
}
return max_area;
}
};
可以在数组最后加入0高度,这样处理即可保证,遍历到最后一个元素时,栈中所有元素均可弹出。
class Solution {
public:
int largestRectangleArea(vector<int>& hist) {
hist.push_back(0);
int n = hist.size();
stack<int> s;
int max_area = 0; // Initialize max area
int tp; // To store top of stack
int area_with_top; // To store area with top bar
// as the smallest bar
int i = 0;
while (i < n) {
if (s.empty() || hist[i] > hist[s.top()])
s.push(i++);
else {
tp = s.top();
s.pop();
area_with_top = hist[tp] * (s.empty() ? i : i - s.top() - 1);
max_area = max(max_area, area_with_top);
}
}
return max_area;
}
};
Approach 2 动画演示: