Skip to content

Commit 08d6432

Browse files
authored
Create 3346. Maximum Frequency of an Element After Performing Operations I
1 parent 93cf494 commit 08d6432

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
class Solution {
2+
public:
3+
int maxFrequency(vector<int>& nums, int k, int numOperations) {
4+
const int MAXN = 200005;
5+
static vector<int> freq(MAXN), prefixSum(MAXN);
6+
7+
int maxValue = (*max_element(nums.begin(), nums.end()));
8+
int limit = (maxValue + k + 2);
9+
10+
// Reset frequency array
11+
fill(freq.begin(), freq.begin() + limit, 0);
12+
13+
// Count occurrences of each number
14+
for (int num : nums) {
15+
freq[num]++;
16+
}
17+
18+
// If no operations are allowed, return the highest existing frequency
19+
if (numOperations == 0) {
20+
return (*max_element(freq.begin(), freq.begin() + limit));
21+
} else {
22+
// Build prefix sum array
23+
prefixSum[0] = freq[0];
24+
for (int i = 1; i < limit; i++) {
25+
prefixSum[i] = (prefixSum[i - 1] + freq[i]);
26+
}
27+
28+
int best = 0;
29+
30+
// Check each possible target value
31+
for (int target = 0; target <= maxValue; target++) {
32+
int left;
33+
if (target > k) {
34+
left = (target - k);
35+
} else {
36+
left = 0;
37+
}
38+
39+
int right;
40+
if ((target + k) < limit) {
41+
right = (target + k);
42+
} else {
43+
right = (limit - 1);
44+
}
45+
46+
int total = (prefixSum[right] - ((left > 0) ? prefixSum[left - 1] : 0));
47+
int changeable = (total - freq[target]);
48+
49+
int possible;
50+
if (numOperations < changeable) {
51+
possible = (freq[target] + numOperations);
52+
} else {
53+
possible = (freq[target] + changeable);
54+
}
55+
56+
if (possible > best) {
57+
best = possible;
58+
}
59+
}
60+
61+
return best;
62+
}
63+
}
64+
};

0 commit comments

Comments
 (0)