-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNextsmaller.java
More file actions
28 lines (27 loc) · 778 Bytes
/
Copy pathNextsmaller.java
File metadata and controls
28 lines (27 loc) · 778 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
import java.util.*;
public class Nextsmaller {
public static void nextSmaller(int arr[], int arr1[]){
Stack <Integer> s = new Stack<>();
for(int i = arr.length-1; i>=0; i--){
//while loop
while(!s.isEmpty() && arr[s.peek()] >= arr[i]){
s.pop();
}
if(s.isEmpty()){
arr1[i] = -1;
}
else{
arr1[i] = arr[s.peek()];
}
s.push(i);
}
}
public static void main(String args[]){
int arr[] = {1,2,3,4,3};
int nSmaller[] = new int[arr.length];
nextSmaller(arr, nSmaller);
for(int i = 0;i<nSmaller.length; i++){
System.out.print(nSmaller[i] + " ");
}
}
}