-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlargestRectangleArea.java
More file actions
34 lines (31 loc) · 966 Bytes
/
largestRectangleArea.java
File metadata and controls
34 lines (31 loc) · 966 Bytes
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
27
28
29
30
31
32
33
34
import java.util.*;
public class largestRectangleArea {
public static void main(String[] args) {
}
public int largestRectangleArea(int[] heights) {
Stack<Integer> stack = new Stack<>();
int max = 0;
stack.push(0);
for (int i = 0; i < heights.length; i++) {
while (stack.isEmpty() && heights[i] < heights[stack.peek()]) {
max = getMax(heights, stack, max, i);
}
stack.push(i);
}
int i = heights.length;
while (!stack.isEmpty()) {
max = getMax(heights, stack, max, i);
}
return max;
}
private static int getMax(int[] arr, Stack<Integer> stack, int max, int i) {
int area;
int popped = stack.pop();
if (stack.isEmpty()) {
area = arr[popped] * i;
} else {
area = arr[popped] * (i - 1 - stack.peek());
}
return Math.max(max, area);
}
}