-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecretArray.java
More file actions
59 lines (50 loc) · 1.63 KB
/
SecretArray.java
File metadata and controls
59 lines (50 loc) · 1.63 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
56
57
58
59
import java.util.*;
public class SecretArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = scanner.nextInt();
}
int[] nge = new int[N];
Arrays.fill(nge, -1);
Stack<Integer> stack = new Stack<>();
for (int i = N - 1; i >= 0; i--) {
while (!stack.isEmpty() && arr[stack.peek()] <= arr[i]) {
stack.pop();
}
if (!stack.isEmpty()) {
nge[i] = arr[stack.peek()];
}
stack.push(i);
}
Map<Integer, Integer> nseMap = new HashMap<>();
stack.clear();
for (int i = N - 1; i >= 0; i--) {
while (!stack.isEmpty() && arr[stack.peek()] >= arr[i]) {
stack.pop();
}
if (!stack.isEmpty()) {
nseMap.put(arr[i], arr[stack.peek()]);
} else {
nseMap.put(arr[i], -1);
}
stack.push(i);
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < N; i++) {
int nextGreater = nge[i];
if (nextGreater == -1) {
result.append("-1");
} else {
result.append(nseMap.getOrDefault(nextGreater, -1));
}
if (i < N - 1) {
result.append(" ");
}
}
System.out.println(result.toString());
scanner.close();
}
}