Apply Operations on Array to Maximize Sum of Squares

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 10^9 + 7.

Example 1
Inputnums = [2,6,5,8], k = 2
Output261
After applying operations, we can choose 15 and 6 from the final array, giving 15^2 + 6^2 = 261, which is maximum.
Example 2
Inputnums = [4,5,4,7], k = 3
Output90
No operations are needed, and choosing 7, 5, and 4 gives 7^2 + 5^2 + 4^2 = 90, which is maximum.

Constraints

  • 1 <= k <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^9

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate