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