-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
41 lines (37 loc) · 1.03 KB
/
Solution.cs
File metadata and controls
41 lines (37 loc) · 1.03 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
public class Solution
{
public int MaxFrequency(int[] nums, int k, int numOperations)
{
int n = nums.Length;
Dictionary<int, int> count = [];
int ans = 0, i = 0, j = 0;
// case 1: [num-k, num+k]
foreach (int num in nums)
{
while (j < n && nums[j] <= num + k)
{
count[nums[j]] = count.GetValueOrDefault(nums[j], 0) + 1;
j++;
}
while (i < n && nums[i] < num - k)
{
count[nums[i]] = count.GetValueOrDefault(nums[i], 0) - 1;
i++;
}
ans = Math.Max(ans, Math.Min(j - i, numOperations + count.GetValueOrDefault(num, 0)));
}
// case 2: [num, num+2k]
i = 0;
j = 0;
while (j < n)
{
while (i < n && nums[j] - nums[i] > 2 * k)
{
i++;
}
ans = Math.Max(ans, Math.Min(j - i + 1, numOperations));
j++;
}
return ans;
}
}