Skip to content

Commit 2bb3f18

Browse files
authored
Implement maxFrequency method for frequency calculation
1 parent 11d8a8f commit 2bb3f18

1 file changed

Lines changed: 63 additions & 0 deletions

File tree

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
class LC_maxfreqeleafterop1 {
2+
3+
public int maxFrequency(int[] nums, int k, int numOperations) {
4+
Arrays.sort(nums);
5+
6+
int ans = 0;
7+
Map<Integer, Integer> numCount = new HashMap<>();
8+
9+
int lastNumIndex = 0;
10+
for (int i = 0; i < nums.length; ++i) {
11+
if (nums[i] != nums[lastNumIndex]) {
12+
numCount.put(nums[lastNumIndex], i - lastNumIndex);
13+
ans = Math.max(ans, i - lastNumIndex);
14+
lastNumIndex = i;
15+
}
16+
}
17+
18+
numCount.put(nums[lastNumIndex], nums.length - lastNumIndex);
19+
ans = Math.max(ans, nums.length - lastNumIndex);
20+
21+
for (int i = nums[0]; i <= nums[nums.length - 1]; i++) {
22+
int l = leftBound(nums, i - k);
23+
int r = rightBound(nums, i + k);
24+
int tempAns;
25+
if (numCount.containsKey(i)) {
26+
tempAns = Math.min(r - l + 1, numCount.get(i) + numOperations);
27+
} else {
28+
tempAns = Math.min(r - l + 1, numOperations);
29+
}
30+
ans = Math.max(ans, tempAns);
31+
}
32+
33+
return ans;
34+
}
35+
36+
private int leftBound(int[] nums, int value) {
37+
int left = 0;
38+
int right = nums.length - 1;
39+
while (left < right) {
40+
int mid = (left + right) / 2;
41+
if (nums[mid] < value) {
42+
left = mid + 1;
43+
} else {
44+
right = mid;
45+
}
46+
}
47+
return left;
48+
}
49+
50+
private int rightBound(int[] nums, int value) {
51+
int left = 0;
52+
int right = nums.length - 1;
53+
while (left < right) {
54+
int mid = (left + right + 1) / 2;
55+
if (nums[mid] > value) {
56+
right = mid - 1;
57+
} else {
58+
left = mid;
59+
}
60+
}
61+
return left;
62+
}
63+
}

0 commit comments

Comments
 (0)