1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Solution { public int largestRectangleArea(int[] heights) { int[] heightsWithSentinel = new int[heights.length + 2]; for (int i = 0; i < heights.length; i++) { heightsWithSentinel[i + 1] = heights[i]; } heights = heightsWithSentinel;
int maxArea = 0; Stack<Integer> increaseStack = new Stack<>();
for (int i = 0; i < heights.length; i++) { while (!increaseStack.isEmpty() && heights[i] < heights[increaseStack.peek()]) { int height = heights[increaseStack.pop()]; int rightIndex = i; int leftIndex = increaseStack.peek(); int width = rightIndex - leftIndex - 1; maxArea = Math.max(maxArea, height * width); }
increaseStack.push(i); }
return maxArea; } }
|
References
84. Largest Rectangle in Histogram
剑指 Offer II 039. 直方图最大矩形面积