1. Description
Given an integer array nums and a positive integer k, you may repeatedly select two different positions and replace their values a and b with a AND b and a OR b, respectively. Both bitwise results use the values before the operation.
After any number of operations, including zero, select k elements. Maximize the sum of their squares and return that maximum modulo 10$^9$ + 7.
2. Example
Example 1
Input: nums = [2,6,5,8], k = 2
Output: 261
Explanation: Combining 2 with 8 gives [0,6,5,10]. Combining 5 with 10 then gives [0,6,0,15]. Select 15 and 6 to obtain 15$^2$ + 6$^2$ = 261.
Example 2
Input: nums = [4,5,4,7], k = 3
Output: 90
Explanation: Select 7, 5, and 4 without changing the array, giving 7$^2$ + 5$^2$ + 4$^2$ = 90.
3. Constraints
- 1 <= k <= nums.length <= 10$^5$
- 1 <= nums[i] <= 10$^9$
4. Solutions
Greedy with Bit Counting
n = nums.size()
Time complexity: O(n)
Space complexity: O(1)
| |