解法1(超出时间限制):
class Solution {
public int largestRectangleArea(int[] heights) {
int length = heights.length;
int max = 0;
for (int i = 0; i < length; i++) {
int index = i - 1, width = 1;
while (index >= 0 && heights[i] <= heights[index]) {
width++;
index--;
}
index = i + 1;
while (index < length && heights[i] <= heights[index]) {
width++;
index++;
}
max = Math.max(max, width * heights[i]);
}
return max;
}
}
解法2:单调栈
class Solution {
public int largestRectangleArea(int[] heights) {
// 将旧数组存储到新数组中
int length = heights.length;
int[] newHeight = new int[length + 2];
for (int i = 0; i < length; i++) {
newHeight[i + 1] = heights[i];
}
// 创建栈(单调栈),并通过遍历找到某一个柱体左右两边比它矮的柱体
LinkedList<Integer> stack = new LinkedList<>();
int max = 0;
length = newHeight.length;
for (int i = 0; i < length; i++) {
while (!stack.isEmpty() && newHeight[i] < newHeight[stack.peek()]) {
int height = newHeight[stack.pop()];
max = Math.max(max, (i - stack.peek() - 1) * height);
}
stack.push(i);
}
return max;
}
}