-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNextGreatestElement.java
More file actions
55 lines (44 loc) · 1.19 KB
/
NextGreatestElement.java
File metadata and controls
55 lines (44 loc) · 1.19 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
package learn.ds.stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* @author Varma Penmetsa
*
* https://www.geeksforgeeks.org/next-greater-element/
*/
public class NextGreatestElement {
public static List<Integer> getNGE(int[] array) {
List<Integer> list = new ArrayList<>();
if (array.length == 0) {
return list;
}
Stack<Integer> st = new Stack<>();
st.push(array[0]);
for (int i = 1; i < array.length; i++) {
int prev = st.pop();
int curr = array[i];
while (prev < curr) {
list.add(curr);
System.out.println(prev+"-->"+curr);
if(st.isEmpty()){
break;
}
prev = st.pop();
}
if(prev > curr){
st.push(prev);
}
st.push(curr);
}
while(!st.isEmpty()){
int prev = st.pop();
System.out.println(prev+"--> -1");
list.add(-1);
}
return list;
}
public static void main(String[] args) {
getNGE(new int[]{9,64,8,5,6,9});
}
}