-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNGR.java
More file actions
57 lines (38 loc) · 1.58 KB
/
Copy pathNGR.java
File metadata and controls
57 lines (38 loc) · 1.58 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
// Nearest Greatest to the Right or next largest number to the right
// Youtube : https://www.youtube.com/watch?v=NXOOYYwpbg4&list=PL_z_8CaSLPWdeOezg68SKkeLN4-T_jNHd&index=2
//TC = O(n)
import java.io.*;
import java.util.*;
public class NGR{
public static List<Integer> getTheNearestGreatertNumberToTheRight(int[] a){
List<Integer> res = new ArrayList<>();
Stack<Integer> s = new Stack<Integer>();
for(int i =a.length-1;i>=0;i--){
//Check if stack is empty
if(s.size() == 0){
res.add(0,-1);
//If top of stack is greater than a[i]
}else if(s.size() > 0 && s.peek() > a[i]){
res.add(0,s.peek());
//If top of stack is less than a[i]
}else if (s.size() > 0 && s.peek() <= a[i]){
//pop until stack is empty or top > a[i]
while(s.size() > 0 && s.peek() <= a[i]){
s.pop();
}
if(s.size() == 0){
res.add(0,-1);
}else{
res.add(0,s.peek());
}
}
s.push(a[i]);
}
return res;
}
public static void main(String[] args){
int[] a = {2 , 3 , 0, 5};
System.out.println("The nearest greater number to the right is "+ getTheNearestGreatertNumberToTheRight(a));
}
}
//o/p:- The nearest greater number to the right is [3, 5, 5, -1]