LeetCode solutions

3622. Maximum Frequency of an Element After Performing Operations I

My accepted Python solution to LeetCode problem 3622, Maximum Frequency of an Element After Performing Operations I, running in 2046ms.

  • Difficulty: Medium
  • Python
  • Runtime 2046ms
  • Memory 39.3MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 2046ms, memory 39.3MB, accepted 2025-12-31.

python
class Solution:
    def maxFrequency(self, nums: List[int], k: int, numOperations: int) -> int:
        from collections import Counter
        
        nums.sort()
        n = len(nums)
        cnt = Counter(nums)
        
        # For each potential target value, we can reach it from nums[i] if |nums[i] - target| <= k
        # We need to find the best target
        
        # Potential targets: each nums[i] or nums[i] - k or nums[i] + k might be optimal
        candidates = set()
        for x in nums:
            candidates.add(x)
            candidates.add(x - k)
            candidates.add(x + k)
        
        ans = 0
        for target in candidates:
            # Count how many elements are already equal to target
            already = cnt[target]
            # Count how many elements can be modified to target (within range and not already equal)
            # Elements in range [target - k, target + k] can be modified to target
            left = 0
            right = n - 1
            # Binary search for left bound: smallest index with nums[i] >= target - k
            lo, hi = 0, n
            while lo < hi:
                mid = (lo + hi) // 2
                if nums[mid] >= target - k:
                    hi = mid
                else:
                    lo = mid + 1
            left = lo
            
            # Binary search for right bound: largest index with nums[i] <= target + k
            lo, hi = 0, n
            while lo < hi:
                mid = (lo + hi) // 2
                if nums[mid] > target + k:
                    hi = mid
                else:
                    lo = mid + 1
            right = lo - 1
            
            if right >= left:
                can_modify = right - left + 1 - already  # Elements that can be modified (excluding already equal)
                ops_used = min(can_modify, numOperations)
                ans = max(ans, already + ops_used)
        
        return ans

Source