- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_3318.java
59 lines (53 loc) · 1.91 KB
/
_3318.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
47
48
49
50
51
52
53
54
55
56
57
58
59
packagecom.fishercoder.solutions.fourththousand;
importjava.util.HashMap;
importjava.util.Map;
importjava.util.PriorityQueue;
publicclass_3318 {
publicstaticclassSolution1 {
publicint[] findXSum(int[] nums, intk, intx) {
PriorityQueue<int[]> maxHeap =
newPriorityQueue<>(
(a, b) ->
a[1] != b[1]
? b[1] - a[1]
: b[0] - a[0]); // a[0] is the number itself, a[1]
// is the frequency
Map<Integer, int[]> map = newHashMap<>();
inti = 0;
for (; i < k; i++) {
int[] a = map.getOrDefault(nums[i], newint[2]);
a[0] = nums[i];
a[1]++;
map.put(nums[i], a);
}
maxHeap.addAll(map.values());
int[] ans = newint[nums.length - k + 1];
for (intj = i - 1, p = 0; j < nums.length; ) {
ans[p++] = computeTopX(newPriorityQueue<>(maxHeap), x);
j++;
if (j >= nums.length) {
break;
}
int[] a = map.getOrDefault(nums[j], newint[2]);
a[0] = nums[j];
a[1]++;
map.put(nums[j], a);
a = map.getOrDefault(nums[j - k], newint[2]);
a[0] = nums[j - k];
a[1]--;
map.put(nums[j - k], a);
maxHeap.clear();
maxHeap.addAll(map.values());
}
returnans;
}
privateintcomputeTopX(PriorityQueue<int[]> maxHeap, intx) {
intsum = 0;
while (!maxHeap.isEmpty() && x-- > 0) {
int[] a = maxHeap.poll();
sum += a[0] * a[1];
}
returnsum;
}
}
}