给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
示例 1:
输入:heights = [2,1,5,6,2,3] 输出:10 解释:最大的矩形为图中红色区域,面积为 10
示例 2:
输入: heights = [2,4] 输出: 4
class Solution {
public int largestRectangleArea(int[] heights) {
if(heights == null) {
return 0;
}
int N = heights.length;
if(N == 0) {
return 0;
} else if(N == 1) {
return heights[0];
}
int ans = heights[0];
LinkedList<Integer> queue = new LinkedList<>();
queue.addLast(0);
for(int ri = 1; ri < N; ri++) {
while(!queue.isEmpty()
&& heights[queue.getLast()] > heights[ri]) {
int now = queue.removeLast();
int le = queue.isEmpty() ? -1 : queue.getLast();
int arr = (ri - le - 1) * heights[now];
if(arr > ans) {
ans = arr;
}
}
queue.addLast(ri);
}
while(!queue.isEmpty()) {
int now = queue.removeLast();
int le = queue.isEmpty() ? -1 : queue.getLast();
int arr = (N - le - 1) * heights[now];
if(arr > ans) {
ans = arr;
}
}
return ans;
}
}
1万+

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



