-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNearestSmallerValues.java
More file actions
41 lines (39 loc) · 1.02 KB
/
NearestSmallerValues.java
File metadata and controls
41 lines (39 loc) · 1.02 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
import java.io.*;
import java.util.*;
class Pair{
int val;
int i;
Pair(int val, int i) {
this.val = val;
this.i = i;
}
}
class NearestSmallerValues {
public static void main (String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Stack<Pair> st = new Stack<>();
int n = Integer.parseInt(br.readLine());
String s[] = br.readLine().split(" ");
int a[] = new int[n];
for(int i = 0; i < n; i++) {
a[i] = Integer.parseInt(s[i]);
}
int ans[] = new int[n];
for(int i = 0; i < n; i++) {
while(!st.isEmpty() && st.peek().val >= a[i]) {
st.pop();
}
if(st.isEmpty()) {
ans[i] = 0;
}
else if(st.peek().val < a[i]) {
ans[i] = st.peek().i + 1;
}
st.push(new Pair(a[i], i));
}
for(int i = 0; i < n; i++) {
System.out.print(ans[i] +" ");
}
}
}