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:
85
💡 Note:
After operations, we can achieve [6,7] by optimally distributing bits. Sum = 6² + 7² = 36 + 49 = 85.
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:
245
💡 Note:
Optimal distribution concentrates bits to maximize the 3 largest values, achieving maximum sum of squares.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 109
- 1 ≤ k ≤ nums.length
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Given array [2,6,4] and k=2, analyze bit patterns
2
Bit Operations
Use AND/OR operations to redistribute bits optimally
3
Maximize Output
Select k=2 largest values and calculate sum of squares
Key Takeaway
🎯 Key Insight: AND/OR operations preserve bit totals - the optimal strategy concentrates bits to maximize squares
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code