这种实在是,。,。记得有几种类型的题都是两个指针中间挤,其实这里是一点思路都没有,因为涉及到保留之前的数据,两个指针就不是那么好用了。下面这种解法还是比较新奇的,用一个栈来保留前面递增的索引号,然后从当前索引往前面进行倒推计算。
public int largestRectangleArea(int[] heights) {
if (heights == null || heights.length == 0) {
return 0;
}
Stack<Integer> stack = new Stack<>();
int max = Integer.MIN_VALUE;
int current = 0;
for (int i = 0; i <= heights.length; i++) {
if (i != heights.length - 1) {
current = -1;
} else {
current = heights[i];
}
while (!stack.isEmpty() && current <= heights[stack.peek()]) {
int height = heights[stack.pop()];
int w = 0;
//栈为空的条件要注意,这里的stack为空的时候可能是前面历史留下来的
if (stack.isEmpty()) {
w = i;
} else {
w = i - stack.peek() - 1;
}
max = Math.max(max, height * w);
}
stack.push(i);
}
return max;
}