-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargestHistogram.java
More file actions
80 lines (65 loc) · 2 KB
/
LargestHistogram.java
File metadata and controls
80 lines (65 loc) · 2 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package Stacks;
import java.util.Stack;
public class LargestHistogram {
public static int largestRectangleArea(int[] heights) {
int n = heights.length;
Stack<Integer> st = new Stack<>();
int[] nse = new int[n];
int[] pse = new int[n];
// Calculate nse[]
st.push(n - 1);
nse[n - 1] = n;
for (int i = n - 2; i >= 0; i--) {
while (st.size() > 0 && heights[st.peek()] >= heights[i]) {
st.pop();
}
if (st.size() == 0)
nse[i] = n;
else
nse[i] = st.peek();
st.push(i);
}
// Emptying Stack
while (st.size() > 0)
st.pop();
// Calculate pse[]
st.push(0);
pse[0] = -1;
for (int i = 1; i <= n - 1; i++) {
while (st.size() > 0 && heights[st.peek()] >= heights[i]) {
st.pop();
}
if (st.size() == 0)
pse[i] = -1;
else
pse[i] = st.peek();
st.push(i);
}
int max = -1;
for (int i = 0; i < n; i++) {
int area = heights[i] * (nse[i] - pse[i] - 1);
max = Math.max(max, area);
}
return max;
}
public static long getMaxArea(long[] hist, long n) {
Stack<Integer> st = new Stack<>();
long maxArea = 0;
for (int i = 0; i <= n; i++) {
while (!st.isEmpty() && (i == n || hist[st.peek()] >= hist[i])) {
long height = hist[st.pop()];
long width;
if (st.isEmpty()) width = i;
else width = i - st.peek() - 1;
long area = width * height;
maxArea = Math.max(area, maxArea);
}
st.push(i);
}
return maxArea;
}
public static void main(String[] args) {
int[] heights = {2, 1, 5, 6, 2, 3};
System.out.println(largestRectangleArea(heights));
}
}