forked from hardikagarwal2001/Hackoctober
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNearestSmallerToRight.java
More file actions
34 lines (28 loc) · 865 Bytes
/
NearestSmallerToRight.java
File metadata and controls
34 lines (28 loc) · 865 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
public class NearestSmallerToRight {
public static void main(String[] args) {
int [] arr = {4,5,2,10,8};
int size = arr.length;
StackImplementationForInt stack = new StackImplementationForInt(size);
int [] near = new int[size];
int i = size-1;
int j = size -1;
while(i>-1){
if(stack.isEmpty()){
near[j] = -1;
stack.push(arr[i]);
i--;j--;
}
else if (stack.peek() < arr[i]){
near[j] = stack.peek();
stack.push(arr[i]);
i--;j--;
}
else if( stack.peek() >= arr[i]){
stack.pop();
}
}
for (int k : near) {
System.out.print(k + " ");
}
}
}