Taro Logo

Apply Operations on Array to Maximize Sum of Squares

#3 Most AskedHard
0 views
Topics:
ArraysGreedy AlgorithmsBit Manipulation

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

You can do the following operation on the array any number of times:

  • Choose any two distinct indices i and j and simultaneously update the values of nums[i] to (nums[i] AND nums[j]) and nums[j] to (nums[i] OR nums[j]). Here, OR denotes the bitwise OR operation, and AND denotes the bitwise AND operation.

You have to choose k elements from the final array and calculate the sum of their squares.

Return the maximum sum of squares you can achieve.

Since the answer can be very large, return it modulo 109 + 7.

Example 1:

Input: nums = [2,6,5,8], k = 2
Output: 261
Explanation: We can do the following operations on the array:
- Choose i = 0 and j = 3, then change nums[0] to (2 AND 8) = 0 and nums[3] to (2 OR 8) = 10. The resulting array is nums = [0,6,5,10].
- Choose i = 2 and j = 3, then change nums[2] to (5 AND 10) = 0 and nums[3] to (5 OR 10) = 15. The resulting array is nums = [0,6,0,15].
We can choose the elements 15 and 6 from the final array. The sum of squares is 152 + 62 = 261.
It can be shown that this is the maximum value we can get.

Example 2:

Input: nums = [4,5,4,7], k = 3
Output: 90
Explanation: We do not need to apply any operations.
We can choose the elements 7, 5, and 4 with a sum of squares: 72 + 52 + 42 = 90.
It can be shown that this is the maximum value we can get.

Constraints:

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

Solution


Brute Force Solution

Approach

The bitwise operation allows shifting bits from one number to another, preserving the total count of set bits at each bit position across the array. Because the square function is strictly convex, concentrating bits into the largest possible values maximizes the sum of squares. Therefore, we can count the frequency of each bit across all numbers and greedily build the k largest possible integers.

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

  1. Initialize an array to count the occurrences of set bits at each bit index from 0 to 30.
  2. Iterate through every integer in the input list and increment the corresponding bit counts.
  3. Set up an accumulator for the total sum of squares and define the modulo constant.
  4. Repeat k times to form the k largest numbers by setting every bit that still has a remaining count greater than zero.
  5. Decrement the used bit counts and add the square of each formed integer to the running total.
  6. Return the final sum modulo 10^9 + 7.

Code Implementation

def max_sum_of_squares(nums: list[int], k: int) -> int:
    modulo = 10**9 + 7
    # Count the number of set bits at each bit position up to 30.
    bit_counts = [0] * 31
    for number in nums:
        for bit_index in range(31):
            if (number >> bit_index) & 1:
                bit_counts[bit_index] += 1
    
    total_sum_of_squares = 0
    # Greedily construct the largest k numbers using the available bits.
    for step in range(k):
        current_value = 0
        for bit_index in range(31):
            if bit_counts[bit_index] > 0:
                current_value |= (1 << bit_index)
                bit_counts[bit_index] -= 1
        # Add the square of the constructed value to the running total modulo 10^9 + 7.
        total_sum_of_squares = (total_sum_of_squares + current_value * current_value) % modulo
        
    return total_sum_of_squares

Big(O) Analysis

Time Complexity
O(N * B + k * B) – Here N is the number of elements in nums and B is the number of bits (which is at most 31 for values up to 10^9). We scan all bits for each number once, and then construct k numbers with 31 bit checks each, making the total operations roughly 31 * (N + k).
Space Complexity
O(B) – Only an array of size 31 is allocated to store the frequencies of set bits across all bit positions.

Optimal Solution

Approach

To maximize the sum of squared values after sharing points around, we need to realize that making a few numbers very large yields a much bigger sum than making many numbers moderately large. The optimal strategy is to collect all the available points and give them to the starting numbers that are already the biggest.

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

  1. Look at all the available numbers and check their binary building blocks, specifically noting how many numbers have a building block present at each position.
  2. Understand that if you take a point from a smaller number and give it to a larger number, the total sum of squares always increases.
  3. To make the final sum as large as possible, you want to concentrate as many building blocks as you can into the numbers that start out the largest.
  4. Go through each building block position from most important to least important, and count how many numbers have that building block.
  5. Form your final top group of numbers by taking the building blocks from the most frequent positions and packing them tightly into the largest available starting numbers.
  6. Calculate the final squared values for this top group and sum them up.
  7. Remember to keep the final sum within safe boundaries by wrapping the math around the standard large limit used in these types of puzzles.

Code Implementation

class Solution:
    def maximize_sum_of_squares(self, numbers_list: list[int], operation_count: int) -> int:
        bit_frequencies = [0] * 30

        # Count building blocks across all numbers to know available power.
        for current_number in numbers_list:
            for bit_index in range(30):
                if (current_number >> bit_index) & 1:
                    bit_frequencies[bit_index] += 1

        reconstructed_numbers = [0] * len(numbers_list)

        # Pack bits tightly into largest possible elements for max squares.
        for element_index in range(len(numbers_list)):
            current_built_value = 0
            for bit_index in range(30):
                if bit_frequencies[bit_index] > element_index:
                    current_built_value |= (1 << bit_index)
            reconstructed_numbers[element_index] = current_built_value

        modulo_limit = 10**9 + 7
        total_sum_squares = 0

        # Sum squares while keeping values within safe boundaries.
        for number_value in reconstructed_numbers:
            total_sum_squares = (total_sum_squares + number_value * number_value) % modulo_limit

        return total_sum_squares

Big(O) Analysis

Time Complexity
O(n log M) – The time complexity is driven by two main phases. First, counting the frequency of bits across all n numbers takes O(n log M) time, where M is the maximum possible value in the array, because each number has at most log M bits. Second, reconstructing the top numbers and computing their sum of squares takes an additional O(n) operations. Combining these phases, the total operations scale as approximately n log M + n, which simplifies to the final Big O time complexity of O(n log M).
Space Complexity
O(32) – To analyze the binary building blocks across the input elements, the algorithm requires auxiliary space to store counts for each of the 32 bit positions. This frequency array of fixed size 32 does not scale with the input size N, since integers are capped at 32 bits. Consequently, the auxiliary space complexity simplifies to O(1) constant space, as the memory footprint remains entirely independent of the number of elements in the array.

Edge Cases

Array of size 1 or 0 elements
How to Handle:
Return the sum of squares of the existing elements directly since no operations can be performed.
Number of operations k is zero
How to Handle:
Skip all bitwise modifications and compute the sum of squares of the original array elements modulo 10^9 + 7.
Array containing all zeros
How to Handle:
Operations will keep all elements as zero, resulting in a total sum of squares equal to zero.
Extremely large array size and maximum element values
How to Handle:
Use a bit-frequency counting array of size 30 and a greedy reconstruction method to ensure O(N) time complexity.
Integer overflow during sum of squares calculation
How to Handle:
Accumulate products using 64-bit integers and apply modulo 10^9 + 7 at each addition step.
Bitwise operations moving bits from lower to upper elements
How to Handle:
Collect all set bits across the entire array into a bit frequency array and greedily form the largest possible numbers.
0/45 completed