-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC84_LargestRectangleInHistogram.java
More file actions
42 lines (35 loc) · 1.11 KB
/
LC84_LargestRectangleInHistogram.java
File metadata and controls
42 lines (35 loc) · 1.11 KB
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
35
36
37
38
39
40
41
42
package practise.src.main.java.leetCode;
import java.util.Stack;
public class LC84_LargestRectangleInHistogram {
public static void main(String[] args) {
int[] heights = {2,1,5,6,2,3};
System.out.println(largestRectangleArea(heights));
}
private static int largestRectangleArea(int[] heights) {
int n = heights.length;
int[] left = new int[n];
int[] right = new int[n];
left[0] = -1;
for (int i = 1; i < n; i++) {
int j = i - 1;
while (j >= 0 && heights[j] >= heights[i]) {
j = left[j];
}
left[i] = j;
}
right[n - 1] = n;
for (int i = n - 2; i >= 0; i--) {
int j = i + 1;
while (j < n && heights[j] >= heights[i]) {
j = right[j];
}
right[i] = j;
}
int maxArea = 0;
for (int i = 0; i < n; i++) {
int width = right[i] - left[i] - 1;
maxArea = Math.max(maxArea, heights[i] * width);
}
return maxArea;
}
}