单调栈/单调队列
别人做的总结
经典题目
public int largestRectangleArea(int[] heights) {
Deque<Integer> stack = new LinkedList<>();
int max = 0;
for (int i = 0; i <= heights.length; i++) {
// To pop out all the elements in the stack at last, so we explicitly add a bar of height 0.
int cur = i == heights.length ? 0 : heights[i];
while (!stack.isEmpty() && heights[stack.peekLast()] >= cur) {
int height = heights[stack.pollLast()];
// Dertermine the left boundary of the largest rectangle with height heights[i]
int left = stack.isEmpty() ? 0 : stack.peekLast() + 1;
// Dertermine the right boundary of the largest rectangle with height of the poped element
max = Math.max(max, height * (i - 1 - left + 1));
}
stack.offerLast(i);
}
return max;
}Last updated