Apply Operations on Array to Maximize Sum of Squares - Problem
You are given a 0-indexed integer array nums and a positive integer k.
You can perform the following operation on the array any number of times:
- Choose any two distinct indices
iandj - Simultaneously update
nums[i]to(nums[i] AND nums[j])andnums[j]to(nums[i] OR nums[j])
Here, OR denotes the bitwise OR operation, and AND denotes the bitwise AND operation.
After performing operations, you must 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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,6,4], k = 2
›
Output:
72
💡 Note:
After operations, we can redistribute bits optimally. With bit counts [0,2,2], we can achieve [0,6,6] by concentrating bits. Taking k=2 largest gives sum = 6² + 6² = 72.
Example 2 — Single Element
$
Input:
nums = [4], k = 1
›
Output:
16
💡 Note:
Only one element, no operations possible. Sum = 4² = 16.
Example 3 — Larger Array
$
Input:
nums = [1,2,3,4,5], k = 3
›
Output:
109
💡 Note:
With nums=[1,2,3,4,5] and k=3, optimal bit distribution concentrates available bits to maximize the sum of squares of the 3 largest values.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 109
- 1 ≤ k ≤ nums.length
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code