2897. Apply Operations on Array to Maximize Sum of Squares
LeetCode Daily Problem: Apply Operations on Array to Maximize Sum of Squares
On this page
You are given a 0-indexed integer array nums and a positive integer k.
You can do the following operation on the array any number of times:
- Choose any two distinct indices
iandjand simultaneously update the values ofnums[i]to(nums[i] AND nums[j])andnums[j]to(nums[i] OR nums[j]). Here,ORdenotes the bitwiseORoperation, andANDdenotes the bitwiseANDoperation.
You have to 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 10^9 + 7.
Constraints:
1 <= k <= nums.length <= 10^51 <= nums[i] <= 10^9
Approach: Greedy
I figured out the math behind this one, but struggled to turn it into code. After reading the solution, I had some ideas, so here is my attempt at an explanation.
Two observations:
The total sum never changes
The operation preserves the total number of 1 bits and 0 bits across the two numbers. The OR result may be larger and the AND result smaller, but the raw materials — the 2^i bits — are never created or destroyed; only their grouping changes.
Maximizing the sum of squares means maximizing the gaps between numbers
By RMS ≥ AM (with equality only when all values are equal), for a fixed sum, the more uneven the values, the larger the sum of squares.
So the problem becomes: using the available 2^i bits, how do we build the largest possible numbers?
The solution uses this idea:
- Count all available
2^iraw materials. - Build the largest possible number: use every bit that is still available.
That is where the greedy choice comes in.
Collecting the raw materials
The solution showed a neat way to take apart a number's binary representation; I learned something:
cnt = [0] * 30
for num in nums:
for i in range(30):
if num & (1 << i): # break into bits
cnt[i] += 1cnt[i] is now the number of available 2^i bits. We use 30 slots because log2(10^9) ≈ 29.897, so the largest bit we need is 2^29; there are 30 bit positions from 2^0 to 2^29.
Greedily assembling
The solution also showed how to assemble:
res = 0
MOD = 10**9 + 7
for _ in range(k):
cur = 0
for j in range(29, -1, -1):
if cnt[j] > 0:
cur |= 1 << j # assemble
cnt[j] -= 1
res = (res + cur * cur) % MODPutting it together gives the final answer.
Complexity
- Time: O(30n + 30k) — one pass to collect bits, then k assembly passes.
- Space: O(30) — constant extra space.