-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay 114.java
More file actions
33 lines (25 loc) · 897 Bytes
/
Day 114.java
File metadata and controls
33 lines (25 loc) · 897 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
33
import java.util.*;
class Solution {
public ArrayList<Integer> nextFreqGreater(int[] arr) {
int n = arr.length;
ArrayList<Integer> result = new ArrayList<>(Collections.nCopies(n, 0));
HashMap<Integer, Integer> freq = new HashMap<>();
for (int x : arr) {
freq.put(x, freq.getOrDefault(x, 0) + 1);
}
Stack<Integer> stack = new Stack<>();
for (int i = n - 1; i >= 0; i--) {
int curr = arr[i];
while (!stack.isEmpty() && freq.get(stack.peek()) <= freq.get(curr)) {
stack.pop();
}
if (stack.isEmpty()) {
result.set(i, -1);
} else {
result.set(i, stack.peek());
}
stack.push(curr);
}
return result;
}
}