-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStacksChapter.java
More file actions
59 lines (53 loc) · 1.62 KB
/
StacksChapter.java
File metadata and controls
59 lines (53 loc) · 1.62 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
import java.util.Stack;
public class StacksChapter {
public static void nxtLstElmnt(int ary[], int grtAry[]) {
Stack<Integer> s = new Stack<>();
for (int i = ary.length - 1; i >= 0; i--) {
while (!s.isEmpty() && ary[i] <= ary[s.peek()]) {
s.pop();
}
if (s.isEmpty()) {
grtAry[i] = -1;
} else {
grtAry[i] = s.peek();
}
s.push(i);
}
}
public static void prvLstElmnt(int ary[], int grtAry[]) {
Stack<Integer> s = new Stack<>();
for (int i = 0; i < ary.length; i++) {
while (!s.isEmpty() && ary[i] <= ary[s.peek()]) {
s.pop();
}
if (s.isEmpty()) {
grtAry[i] = -1;
} else {
grtAry[i] = s.peek();
}
s.push(i);
}
}
public static int maxAreaHistogram(int ary[]) {
int prvLst[] = new int[ary.length];
int nxtLst[] = new int[ary.length];
prvLstElmnt(ary, prvLst);
nxtLstElmnt(ary, nxtLst);
int area, maxArea = Integer.MIN_VALUE;
for (int i = 0; i < ary.length; i++) {
int height = ary[i];
int p = prvLst[i];
int q = nxtLst[i] == -1 ? ary.length : nxtLst[i];
int width = q - p - 1;
area = height * width;
maxArea = Math.max(area, maxArea);
}
return maxArea;
}
public static void main(String[] args) {
int[] ary = {
10, 10
};
System.out.println(maxAreaHistogram(ary));
}
}