Taro Logo

Apply Operations to Maximize Frequency Score

#2 Most AskedHard
Topics:
ArraysBinary SearchSliding WindowsGreedy Algorithms

You are given a 0-indexed integer array nums and an integer k.

You can perform the following operation on the array at most k times:

  • Choose any index i from the array and increase or decrease nums[i] by 1.

The score of the final array is the frequency of the most frequent element in the array.

Return the maximum score you can achieve.

The frequency of an element is the number of occurences of that element in the array.

Example 1:

Input: nums = [1,2,6,4], k = 3
Output: 3
Explanation: We can do the following operations on the array:
- Choose i = 0, and increase the value of nums[0] by 1. The resulting array is [2,2,6,4].
- Choose i = 3, and decrease the value of nums[3] by 1. The resulting array is [2,2,6,3].
- Choose i = 3, and decrease the value of nums[3] by 1. The resulting array is [2,2,6,2].
The element 2 is the most frequent in the final array so our score is 3.
It can be shown that we cannot achieve a better score.

Example 2:

Input: nums = [1,4,4,2,4], k = 0
Output: 3
Explanation: We cannot apply any operations so our score will be the frequency of the most frequent element in the original array, which is 3.

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • 0 <= k <= 1014

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of values for the elements in `nums` and what are the constraints on the size of the array and $k$?
  2. Can the array contain negative numbers, zeros, or can $k$ be zero?
  3. Are duplicates allowed in the input array, and do elements with the same initial value count towards the frequency score?
  4. If multiple target values can achieve the same maximum frequency, does it matter which target value we choose, or can we return the frequency for any of them?
  5. Is the input array guaranteed to be non-empty?

Brute Force Solution

Approach

Imagine you have a collection of numbers and you want to make as many of them as identical as possible by slightly changing their values, up to a limited number of total changes. The brute force approach works by checking every single number in your collection and testing every possible target value to see how many matching numbers you can create.

Here's how the algorithm would work step-by-step:

  1. Pick a starting number from your collection to act as your target value.
  2. Look at all the other numbers and calculate how much effort or how many changes it would take to make them all equal to your chosen target.
  3. Keep adding up these changes for each number one by one, stopping if the total amount of allowed changes runs out.
  4. Count how many numbers successfully reached your target value within the allowed changes.
  5. Repeat this entire process by picking every other number in your collection as the new target.
  6. Compare the results from every single target you tested.
  7. Declare the highest count of matching numbers you found as your final answer.

Code Implementation

def max_frequency_score(numbers_collection, allowed_operations):
    # Sort numbers to evaluate contiguous elements efficiently for any chosen target value
    sorted_numbers = sorted(numbers_collection)
    total_elements = len(sorted_numbers)
    max_frequency_found = 0

    # Test each number in the collection as the potential target value for uniformity
    for target_index in range(total_elements):
        target_value = sorted_numbers[target_index]
        current_operations_used = 0
        matching_count = 0

        # Expand the window outward to include adjacent numbers and calculate operation cost
        for current_index in range(target_index, -1, -1):
            cost_to_reach_target = target_value - sorted_numbers[current_index]
            
            if current_operations_used + cost_to_reach_target > allowed_operations:
                break

            current_operations_used += cost_to_reach_target
            matching_count += 1

        # Track the maximum frequency achieved across all tested target values
        if matching_count > max_frequency_found:
            max_frequency_found = matching_count

    return max_frequency_found

Big(O) Analysis

Time Complexity
O(n²) – For each of n starting numbers chosen as the target value in the collection, the approach iterates through the remaining elements to calculate the total changes needed. For the first target number, we examine up to (n-1) other elements, for the second target (n-2) elements, and so on. This cumulative process results in approximately n * n/2 total operations for the nested evaluations. Simplifying this expression by dropping constants leaves us with a final Big O time complexity of O(n²).
Space Complexity
O(N) – To implement the approach described, we first sort the input array of numbers of size N in place, which requires auxiliary space for the recursion or call stack used by the sorting algorithm. Additionally, calculating the prefix sum array to quickly compute the effort needed to change numbers takes O(N) extra memory. As the input size N increases, these underlying structures scale linearly with the number of elements. Therefore, the total auxiliary space complexity simplifies to Big O of N.

Optimal Solution

Approach

The optimal strategy relies on organizing the given numbers from smallest to largest and using a sliding window to find the longest contiguous group of numbers that can be made equal using a limited number of operations. By checking groups of increasing sizes and shifting them across the sorted values, we efficiently determine the maximum possible frequency without testing every single combination.

Here's how the algorithm would work step-by-step:

  1. First, arrange all the numbers in order from smallest to largest so that numbers with similar values sit right next to each other.
  2. Imagine a sliding window or a flexible bracket that covers a range of these sorted numbers, representing a group you want to make completely identical.
  3. Calculate the total cost in terms of operations required to push every number in the current window up to match the value sitting right in the middle of that window.
  4. If the total cost to equalize the window goes beyond your allowed budget, shrink the window from the left side until it fits within your budget again.
  5. If the cost is within your budget, expand the window to the right to see if you can include even more numbers in your group.
  6. Keep track of the largest window size you are able to achieve while staying within the allowed operation budget.
  7. Slide the window across the entire sorted collection, constantly expanding when affordable and shifting when too expensive, until you find the absolute maximum frequency possible.

Code Implementation

def max_frequency_score(number_list, operation_budget):
    number_list.sort()
    list_length = len(number_list)
    prefix_sums = [0] * (list_length + 1)
    
    for index in range(list_length):
        prefix_sums[index + 1] = prefix_sums[index] + number_list[index]
        
    window_start = 0
    max_frequency = 0
    
    for window_end in range(list_length):
        median_index = (window_start + window_end) // 2
        median_value = number_list[median_index]
        
        left_count = median_index - window_start
        left_cost = median_value * left_count - (prefix_sums[median_index] - prefix_sums[window_start])
        
        right_count = window_end - median_index
        right_cost = (prefix_sums[window_end + 1] - prefix_sums[median_index + 1]) - median_value * right_count
        
        total_cost = left_cost + right_cost
        
        # Shrink the window from the left if operations exceed the allowed budget.
        if total_cost > operation_budget:
            window_start += 1
            
        max_frequency = max(max_frequency, window_end - window_start + 1)
        
    return max_frequency

Big(O) Analysis

Time Complexity
O(n log n) – Sorting the input array of size n takes O(n log n) time as the first major step. The sliding window approach then uses two pointers, a left and a right pointer, that each traverse the sorted array at most once, taking linear O(n) time. The cost calculations and updates within the window operations execute in constant time for each step. Since the logarithmic sorting cost dominates the linear sliding window traversal, the total time complexity simplifies to O(n log n).
Space Complexity
O(log n) or O(n) – The auxiliary space complexity is primarily driven by the sorting operation applied to the input array of size N. Depending on the underlying sorting algorithm implementation used by the programming language, the recursive call stack for sorting requires extra memory proportional to the logarithm of the input size, O(log n), or up to O(n) auxiliary space if additional temporary arrays are allocated. Beyond the sorting process, the sliding window technique only uses a few primitive variables for pointers and cost calculations, which require constant extra space. Therefore, the total auxiliary space complexity is dominated by the sorting step, resulting in O(log n) or O(n) space.

Edge Cases

Single element array where the array length is 1
How to Handle:
Return a frequency of 1 immediately since zero operations are needed to make a single element equal to itself.
All elements are already identical
How to Handle:
The sliding window will encompass the entire array and k operations will not be needed, returning the total length.
The budget k is 0
How to Handle:
The sliding window correctly limits matches to pre-existing duplicate groups in the sorted array, returning the maximum count of identical adjacent elements.
Large k capable of making all elements equal to the maximum value
How to Handle:
The sliding window expands to cover the entire array because the total cost to equalize all elements will be less than or equal to k.
Array contains negative numbers, zeros, and positive numbers mixed together
How to Handle:
Sorting the array normally handles negative values and zeros seamlessly as standard arithmetic distance applies uniformly across the number line.
Extremely large numbers causing integer overflow during cost calculation
How to Handle:
Prefix sums and cost equations must use 64-bit integers to prevent overflow when accumulating differences over large windows.
Maximum constraint inputs with length up to 10 to the 5th power
How to Handle:
An O(n log n) sorting step followed by an O(n) sliding window approach ensures execution well within standard time limits.
All elements are distinct and spread far apart with a small k
How to Handle:
The sliding window shrinks from the left whenever the cost exceeds k, ensuring we always find the optimal contiguous subset of size at least 1.
0/18 completed