Q2. Maximum Frequency of an Element After Performing Operations I Medium 4 pt. You are…
- User
Q2. Maximum Frequency of an Element After Performing Operations I Medium 4 pt. 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.
Example 1:
Input: nums = [1,4,5], k = 1, numOperations = 2
Output: 2
Explanation:
We can achieve a maximum frequency of two by:
Adding 0 to nums[1]. nums becomes [1, 4, 5]. Adding -1 to nums[2]. nums becomes [1, 4, 4]. Example 2:
Input: nums = [5,11,20,20], k = 5, numOperations = 1
Output: 2
Explanation:
We can achieve a maximum frequency of two by:
Adding 0 to nums[1].
Constraints:
1 <= nums.length <= 105 1 <= nums[i] <= 105 0 <= k <= 105 0 <= numOperations <= nums.length class Solution { public: int maxFrequency(vector& nums, int k, int numOperations) {
code}}; c++ code without comments
- Assistantcpp
#include<bits/stdc++.h> using namespace std; class Solution { public: int maxFrequency(vector<int>& nums, int k, int numOperations) { // Define the maximum possible value after adjustments int MAX_VAL = 200000; // Initialize frequency and prefix sum arrays vector<int> freq(MAX_VAL + 2, 0); for(auto num: nums){ freq[num]++; } vector<long long> prefix(MAX_VAL + 2, 0); for(int i=1;i<=MAX_VAL;i++) prefix[i] = prefix[i-1] + freq[i]; int max_freq = 0; for(int t=1;t<=MAX_VAL;t++){ if(freq[t]==0) continue; int l = max(1, t - k); int r = min(MAX_VAL, t + k); long long total_in_window = prefix[r] - prefix[l-1]; long long can_adjust = total_in_window - freq[t]; long long possible = freq[t] + min((long long)can_adjust, (long long)numOperations); max_freq = max(max_freq, (int)possible); } return max_freq; } };