1public int largestRectangleArea(int[] heights) {
2 Stack<Integer> stack = new Stack<>();
3 int maxArea = 0;
4
5 for (int i = 0; i < heights.length; i++) {
6 while (!stack.isEmpty() && heights[i] < heights[stack.peek()]) {
7 int height = heights[stack.pop()];
8 int width = stack.isEmpty() ? i : i - stack.peek() - 1;
9 int currentArea = height * width;
10 maxArea = Math.max(maxArea, currentArea);
11 }
12
13 stack.push(i);
14 }
15
16 while (!stack.isEmpty()) {
17 int height = heights[stack.pop()];
18 int width = stack.isEmpty() ? heights.length : heights.length - stack.peek() - 1;
19 int currentArea = height * width;
20 maxArea = Math.max(maxArea, currentArea);
21 }
22
23 return maxArea;
24}