You're given a 0-indexed integer array nums and a positive integer k. Your goal is to strategically manipulate the array using bitwise operations to maximize the sum of squares of the k largest elements.
Available Operation: Choose any two distinct indices i and j, then simultaneously:
- Update
nums[i]tonums[i] AND nums[j] - Update
nums[j]tonums[i] OR nums[j]
You can perform this operation any number of times. The key insight is that this operation allows you to redistribute bits between array elements - the AND operation concentrates common bits in one element, while the OR operation preserves all bits in the other.
After all operations, select k elements and return the maximum possible sum of their squares modulo 109 + 7.
Example: With nums = [2, 7, 1], k = 2, you can transform the array to maximize two squares by concentrating bits optimally.
Input & Output
Visualization
Time & Space Complexity
30 iterations for each bit position times n elements to count bits
Only using arrays of size 30 for bit counts and k for result
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 109
- 1 ≤ k ≤ nums.length
- Answer must be returned modulo 109 + 7