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: 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
Maximize Sum of Squares INPUT nums array: 2 i=0 6 i=1 4 i=2 Binary View: 010 110 100 Bit Counts per Position: Bit 2: 1+1+1 = 3 Bit 1: 0+1+0 = 1 Bit 0: 0+0+0 = 0 k = 2 ALGORITHM STEPS 1 Count Bits Count 1s at each position 2 Redistribute Bits AND/OR moves bits greedily 3 Build Max Numbers Assign bits to k numbers 4 Calculate Squares Sum squares of k elements Greedy Assignment: Bit 2: 3 ones Bit 1: 1 one num1 = 110 = 6 num2 = 100 = 4 --> 7 (after redistribution) FINAL RESULT Optimal Array: 7 6 0 Choose k=2 largest: 7 6 Calculation: 7^2 + 6^2 = 49 + 36 = 85 Output: 85 Key Insight: AND/OR operations preserve total bit count per position. To maximize sum of squares, concentrate bits into fewer numbers. Greedily assign bits to create k largest values, since squares favor larger numbers. Result: 7^2 + 6^2 = 85 (mod 10^9+7). TutorialsPoint - Apply Operations on Array to Maximize Sum of Squares | Greedy with Priority Queue
Asked in
Google 25 Microsoft 20 Amazon 15
33.0K 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