-
Notifications
You must be signed in to change notification settings - Fork 11
/
nextSmallerBigger.java
92 lines (70 loc) · 2.04 KB
/
nextSmallerBigger.java
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
81
82
83
84
85
86
87
88
89
90
91
92
void solve{
int n= 8;
int[] arr ={1,1,2,4,3,2,4,5};
int[] nheL = new int[n];
int[] nheR = new int[n];
int[] nseR = new int[n];
int[] nseL = new int[n];
LinkedList<Integer> ll = new LinkedList<>();
/*
next higher of arr[i] is first element after arr[i] which >= arr[i]
you can make it strictly > arr[i] by toggling '=' sign
*/
for(int i=0;i<n;++i){
if( ll.isEmpty() || arr[ll.peekLast()] > arr[i]){
ll.add(i);
}
else{
while(!ll.isEmpty() && arr[i]>=arr[ll.peekLast()])
nheR[ll.pollLast()] = i ;
ll.add(i);
}
}
while(!ll.isEmpty()){
nheR[ll.pollLast()] = -1 ;
}
for(int i=n-1;i>=0;--i){
if( ll.isEmpty() || arr[ll.peekLast()] > arr[i]){
ll.add(i);
}
else{
while(!ll.isEmpty() && arr[i]>=arr[ll.peekLast()])
nheL[ll.pollLast()] = i ;
ll.add(i);
}
}
while(!ll.isEmpty()){
nheL[ll.pollLast()] = -1 ;
}
for(int i=0;i<n ; ++i){
if( ll.isEmpty() || arr[ll.peekLast()] < arr[i]){
ll.add(i);
}
else{
while(!ll.isEmpty() && arr[i]<=arr[ll.peekLast()])
nseR[ll.pollLast()] = i ;
ll.add(i);
}
}
while(!ll.isEmpty()){
nseR[ll.pollLast()] = -1 ;
}
for(int i=n-1;i>=0 ; --i){
if( ll.isEmpty() || arr[ll.peekLast()] < arr[i]){
ll.add(i);
}
else{
while(!ll.isEmpty() && arr[i]<=arr[ll.peekLast()])
nseL[ll.pollLast()] = i ;
ll.add(i);
}
}
while(!ll.isEmpty()){
nseL[ll.pollLast()] = -1 ;
}
pn(Arrays.toString(arr));
pn("next smaller R "+Arrays.toString(nseR));
pn("next smaller L "+Arrays.toString(nseL));
pn("next higher R "+Arrays.toString(nheR));
pn("next higher L "+Arrays.toString(nheL));
}