Input: nums =[10,2,3,4,5,5,4,3,2,2], k =10Output: 4Explanation:
After adding 8 to `nums[1..9]`,10 has a frequency of 4in`[10, 10, 11, 12,
13, 13, 12, 11, 10, 10]`.
To maximize the frequency of k after one subarray operation, we want to maximize the number of indices where nums[i] can be made equal to k by adding the same value to a subarray containing i. For each index, the difference d = k - nums[i] tells us how much we need to add at i. We can use a hash map to count the maximum number of indices that can be covered by a single subarray operation for each difference value.
For each possible difference d, use a sliding window to find the maximum number of indices that can be covered by a subarray (i.e., the indices where k - nums[i] == d are consecutive).
The answer is the maximum count among all difference values.
classSolution {
public:int maxFrequency(vector<int>& nums, int k) {
int n = nums.size(), ans =0;
unordered_map<int, int> cnt;
for (int i =0; i < n; ++i) cnt[k - nums[i]]++;
for (auto& [d, c] : cnt) ans = max(ans, c);
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
funcmaxFrequency(nums []int, kint) int {
cnt:=map[int]int{}
for_, v:=rangenums {
cnt[k-v]++ }
ans:=0for_, c:=rangecnt {
ifc > ans {
ans = c }
}
returnans}
1
2
3
4
5
6
7
8
9
classSolution {
publicintmaxFrequency(int[] nums, int k) {
Map<Integer, Integer> cnt =new HashMap<>();
for (int v : nums) cnt.put(k-v, cnt.getOrDefault(k-v, 0)+1);
int ans = 0;
for (int c : cnt.values()) ans = Math.max(ans, c);
return ans;
}
}
1
2
3
4
5
6
7
classSolution {
funmaxFrequency(nums: IntArray, k: Int): Int {
val cnt = mutableMapOf<Int, Int>()
for (v in nums) cnt[k-v] = cnt.getOrDefault(k-v, 0) + 1return cnt.values.maxOrNull() ?:0 }
}
1
2
3
4
5
classSolution:
defmaxFrequency(self, nums: list[int], k: int) -> int:
from collections import Counter
cnt = Counter(k - v for v in nums)
return max(cnt.values())