[LeetCode] Maximum Frequency of an Element After Performing Operations I

3346. Maximum Frequency of an Element After Performing Operations I

You are given an integer array nums and two integers k and numOperations.

You must perform an operation numOperations times on nums, where in each operation you:

  • Select an index i that was not selected in any previous operations.
  • Add an integer in the range [-k, k] to nums[i].

Return the maximum possible frequency of any element in nums after performing the operations.

The frequency of an element x is the number of times it occurs in the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int maxFrequency(vector<int>& nums, int k, int numOperations) {
vector<int> freq(1e5+1);
for(auto& n : nums) freq[n]++;
int res = 0;
for(int i = 0, l = 0, r = 0, cnt = 0; i <= 1e5; i++) {
while(r <= 1e5 and r <= i + k) cnt += freq[r++];
while(l < i - k) cnt -= freq[l++];
res = max(res, freq[i] + min(cnt - freq[i], numOperations));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/11/10/PS/LeetCode/maximum-frequency-of-an-element-after-performing-operations-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.