[LeetCode] Apply Operations to Maximize Frequency Score

2968. Apply Operations to Maximize Frequency Score

You are given a 0-indexed integer array nums and an integer k.

You can perform the following operation on the array at most k times:

  • Choose any index i from the array and increase or decrease nums[i] by 1.

The score of the final array is the frequency of the most frequent element in the array.

Return the maximum score you can achieve.

The frequency of an element is the number of occurences of that element in the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int maxFrequencyScore(vector<int>& A, long long k) {
int i = 0, n = A.size();
sort(A.begin(), A.end());
for (int j = 0; j < n; ++j) {
if ((k -= A[j] - A[(i + j) / 2]) < 0)
k += A[(i + j + 1) / 2] - A[i++];
}

return n - i;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/12/17/PS/LeetCode/apply-operations-to-maximize-frequency-score/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.