-
Notifications
You must be signed in to change notification settings - Fork 0
/
NextGreater.java
46 lines (32 loc) · 933 Bytes
/
NextGreater.java
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
package Stack;
import java.util.Scanner;
import java.util.Stack;
public class NextGreater {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for(int i = 0; i < n; i++){
arr[i] = sc.nextInt();
}
int nextInd[] = new int[n];
Stack<Integer> st = new Stack<>();
int size = 0;
for(int i = 0 ; i <= arr.length - 1; i++){
while(!st.isEmpty() && arr[st.peek()] <= arr[i]){
st.pop();
}
if(st.isEmpty()){
nextInd[i] = 0;
}
else{
nextInd[i] = st.size();
}
st.push(i);
}
for(int i = 0; i < n; i++){
System.out.print(nextInd[i] + " ");
}
System.out.println();
}
}