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 i and j
  • Simultaneously update 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.

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
Apply Operations to Maximize Sum of SquaresInput: [2,6,4], k=22 = 010₂6 = 110₂4 = 100₂Bit DistributionBit 0: 1 occurrenceBit 1: 2 occurrencesBit 2: 2 occurrencesOptimal ResultAfter operations: [6,7]6 = 110₂, 7 = 111₂Sum = 6² + 7² = 85Key Operations: (a AND b, a OR b)Strategy: Concentrate bits in fewer numbers🎯 Key InsightOperations preserve total bits - maximize by optimal distribution
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
Asked in
Google 25 Microsoft 20 Amazon 15
32.9K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen