#3347

Maximum Frequency of an Element After Performing Operations II

Hard
ArrayBinary SearchSliding WindowSortingPrefix SumSliding WindowSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal solution uses sorting and a sliding window approach to efficiently determine the maximum frequency of any element. By sorting the array, we can focus on making elements equal to a target value using the least operations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the array nums.
  2. 2Step 2: Use a sliding window to find the maximum frequency of elements that can be made equal to nums[right] using the allowed operations.
  3. 3Step 3: For each right index, calculate the total operations needed to make all elements in the current window equal to nums[right]. If it exceeds numOperations, move the left index to reduce the window size.
solution.py17 lines
1# Full working Python code
2
3def maxFrequency(nums, k, numOperations):
4    nums.sort()
5    left = 0
6    total = 0
7    max_freq = 0
8    for right in range(len(nums)):
9        total += nums[right]
10        while nums[right] * (right - left + 1) - total > numOperations:
11            total -= nums[left]
12            left += 1
13        max_freq = max(max_freq, right - left + 1)
14    return max_freq
15
16# Example usage
17print(maxFrequency([1, 4, 5], 1, 2))

Complexity note: The sorting step takes O(n log n) time, and the sliding window traversal takes O(n) time, making this approach efficient overall.

  • 1Sorting the array allows us to efficiently determine how many elements can be made equal to a target value.
  • 2Using a sliding window helps us keep track of the number of operations needed dynamically.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.