Leetcode Daily - Maximum Frequency of an Element After Performing Operations I
1. Input, Output, Contraints
- Input:
nums = [1,4,5], k = 1, numOperations = 2
- Output:
now [1,4,4], so max frequency = 2 ✅
- Constraints:
- 1 <= nums.length <= 105
- 1 <= nums[i] <= 105
- 0 <= k <= 105
- 0 <= numOperations <= nums.length
2. Intuitiation (Dry run):
-
Naive solution: Find all the subset items, so that arr[j] - arr[i] >= 2 * k, of course each elements are count 1 time.
-
Optimized solution: Sliding window to move left until right.
3. Naive Solution
class Solution:
def maxFrequency(self, nums: List[int], k: int, numOperations: int) -> int:
nums.sort()
n = len(nums)
res = 1
for i in range(n):
cnt = 1
ops = numOperations
for j in range(n):
if i == j:
continue
if abs(nums[j] - nums[i]) <= 2 * k and ops > 0:
cnt += 1
ops -= 1
res = max(res, cnt)
return res
4. Optimize Solution
class Solution:
def maxFrequency(self, nums: List[int], k: int, numOperations: int) -> int:
nums.sort()
left = 0
res = 1
# current window represents elements we can make equal
for right in range(len(nums)):
# shrink window if we need more changes than allowed
while nums[right] - nums[left] > 2 * k:
left += 1
# number of elements in this window = right - left + 1
# but we can only modify up to numOperations elements
length = right - left + 1
res = max(res, min(length, numOperations + 1)) # +1 for the target element itself
return res
min(length, numOperations + 1)
Why numOperations + 1?
👉 Because:
-
You can change up to numOperations indices. But there’s at least one base element that serves as the “target” (you don’t have to change it).
-
So in the best case:
-
You make the target number itself stay the same,
-
You change up to numOperations others to match it.
-
=> So the maximum possible group size = numOperations + 1.
- For example:
numOperations = 2 → you can have up to 3 equal elements
Last Updated On October 21, 2025