monotonic stack
A monotonic stack, as the name implies, is a stack in which the elements in the stack are monotonically arranged in increasing (decreasing) order.
Monotonically increasing stack:
① Find the first element smaller than it from its right side for each element in a queue
② Find the first element smaller than it from its left side for each element in a queue
Monotonically decreasing stack:
① Find the first element larger than it from its right side for each element in
a queue ② Find the first element larger than it from its left side for each element in a queue
When to use a monotone stack: For any element, find the first position on the left and right that is larger/smaller than itself and use a monotone stack.
Since each element is in and out of the stack at most once, the complexity is O(n).
Leek84
Given n non-negative integers, used to represent the height of each column in the histogram. Each column is adjacent to each other and has a width of 1.
Find the maximum area of the rectangle that can be outlined in the histogram.
Example 1:
Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The largest rectangle is the red area in the figure, with an area of 10
Example 2:
Input: heights = [2,4]
Output: 4
提示:
1 <= heights.length <=105
0 <= heights[i] <= 104
train of thought
The monotonically increasing stack maintains the coordinates of the first column smaller than it on the left when it is pushed into the stack, and maintains the coordinates of the first column smaller than it on the right when it is popped out of the stack.
the code
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int n = heights.size();
vector<int> left(n), right(n, n);
stack<int> mono_stack;
for (int i = 0; i < n; ++i) {
while (!mono_stack.empty() && heights[mono_stack.top()] >= heights[i]) {
right[mono_stack.top()] = i;
mono_stack.pop();
}
left[i] = (mono_stack.empty() ? -1 : mono_stack.top());
mono_stack.push(i);
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans = max(ans, (right[i] - left[i] - 1) * heights[i]);
}
return ans;
}
};