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
| class Solution { public int largestRectangleArea(int[] heights) { int n = heights.length, ans = 0; int[] l = new int[n], r = new int[n]; Arrays.fill(l, -1); Arrays.fill(r, n); Deque<Integer> stack = new ArrayDeque<>(); for (int i = 0; i < n; i++) { while (!stack.isEmpty() && heights[stack.peek()] > heights[i]) r[stack.pop()] = i; stack.push(i); } stack.clear(); for (int i = n - 1; i >= 0; i--) { while (!stack.isEmpty() && heights[stack.peek()] > heights[i]) l[stack.pop()] = i; stack.push(i); } for (int i = 0; i < n; i++) { int height = heights[i], width = r[i] - l[i] - 1; ans = Math.max(ans, height * width); } return ans; } }
|