class Solution {
public int largestRectangleArea(int[] heights) {
int[] newHeight = new int[heights.length + 2];
System.arraycopy(heights, 0, newHeight, 1, heights.length);
newHeight[heights.length+1] = 0;
newHeight[0] = 0;
Stack<Integer> stack = new Stack<>();
stack.push(0);
int res = 0;
for (int i = 1; i < newHeight.length; i++) {
while (newHeight[i] < newHeight[stack.peek()]) {
int mid = stack.pop();
int w = i - stack.peek() - 1;
int h = newHeight[mid];
res = Math.max(res, w * h);
}
stack.push(i);
}
return res;
}
}
训练营第六十天● 84.柱状图中最大的矩形
于 2024-01-27 14:35:02 首次发布
本文介绍了如何使用Java编程语言中的栈数据结构和动态规划方法,解决代码随想录中的最大矩形面积问题,通过维护堆栈来追踪边界,找到具有最大面积的矩形。

被折叠的 条评论
为什么被折叠?



