-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNextGreaterFrequency.java
More file actions
60 lines (46 loc) · 1.44 KB
/
Copy pathNextGreaterFrequency.java
File metadata and controls
60 lines (46 loc) · 1.44 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
60
package Arrays;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class NextGreaterFrequency {
int[] array;
Stack<Pair> stack;
Map<Integer, Integer> map;
static class Pair {
int data;
int freq;
Pair(int d, int f) {
this.data = d;
this.freq = f;
}
}
NextGreaterFrequency(int[] a) {
this.array = a;
this.stack = new Stack<>();
this.map = new HashMap<>();
}
public void solution() {
int[] res = new int[array.length];
for (int j : array) {
map.put(j, map.getOrDefault(j, 0) + 1);
}
res[array.length - 1] = -1;
int current = map.get(array[array.length - 1]);
stack.push(new Pair(array[array.length - 1], current));
for (var i = array.length - 2; i >= 0; i--) {
current = map.get(array[i]);
while (!stack.isEmpty() && current >= stack.peek().freq) {
stack.pop();
}
res[i] = stack.isEmpty() ? -1 : stack.peek().data;
stack.push(new Pair(array[i], current));
}
Arrays.stream(res).forEach(System.out::print);
}
public static void main(String[] args) {
int[] arr = {1, 1, 1, 2, 2, 2, 2, 11, 3, 3};
NextGreaterFrequency nextGreaterFrequency = new NextGreaterFrequency(arr);
nextGreaterFrequency.solution();
}
}