forked from codehouseindia/Java-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNextSmallerElementonRight.java
More file actions
46 lines (42 loc) · 1.02 KB
/
NextSmallerElementonRight.java
File metadata and controls
46 lines (42 loc) · 1.02 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
#https://www.facebook.com/permalink.php?story_fbid=623985158490864&id=100026381556272
# suscribed by chandresh joshi
package com.cjwarrior7.stackandqueue;
import java.util.Stack;
public class DemoNextSmallerElementonRightAlter {
public static void main(String[] args) {
int[] arr= new int[9];
arr[0]=2;
arr[1]=5;
arr[2]=9;
arr[3]=3;
arr[4]=1;
arr[5]=12;
arr[6]=6;
arr[7]=8;
arr[8]=7;
//2 5 9 3 1 12 6 8 7
int[] res=solve(arr);
for (int i = 0; i < res.length ; i++) {
System.out.println(res[i]);
}
}
public static int[] solve(int[] arr){
int[] nge = new int[arr.length];
Stack<Integer> st=new Stack<Integer>();
st.push(0);
for (int i = 1; i <arr.length ; i++) {
while (st.size() > 0 && arr[i] < arr[st.peek()]){
int pos=st.peek();
nge[pos]=arr[i];
st.pop();
}
st.push(i);
}
while (st.size()>0) {
int pos=st.peek();
nge[pos] = -1;
st.pop();
}
return nge;
}
}