-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNextgreater.java
More file actions
32 lines (29 loc) · 841 Bytes
/
Copy pathNextgreater.java
File metadata and controls
32 lines (29 loc) · 841 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
31
32
import java.util.*;
public class Nextgreater {
public static void nextGreater(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();
}
//isempty check
if(s.isEmpty()){
arr1[i] = -1;
}
else{
arr1[i] = arr[s.peek()];
}
//push into the stack
s.push(i);
}
}
public static void main(String args[]){
int arr[] = {1,2,3,4,3};
int nGreater[] = new int[arr.length];
nextGreater(arr, nGreater);
for(int i = 0;i<nGreater.length; i++){
System.out.print(nGreater[i] + " ");
}
}
}