Apply Operations on Array to Maximize Sum of Squares — LeetCode 2897 Python Solution

HardGreedyBit ManipulationArrayHash Table
Problem
#2897
Reading time
4 min

The problem

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 i and j and simultaneously update the values of nums[i] to (nums[i] AND nums[j]) and nums[j] to (nums[i] OR nums[j]).

Example

Input
nums = [2,6,5,8], k = 2
Output
261
Explanation
We can do the following operations on the array:

Python solution

Python
class Solution:
    def maxSum(self, nums: List[int], k: int) -> int:
        mod = 10**9 + 7
        cnt = [0] * 31
        for x in nums:
            for i in range(31):
                if x >> i & 1:
                    cnt[i] += 1
        ans = 0
        for _ in range(k):
            x = 0
            for i in range(31):
                if cnt[i]:
                    x |= 1 << i
                    cnt[i] -= 1
            ans = (ans + x * x) % mod
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log M)
SpaceO(\log M) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2897. Apply Operations on Array to Maximize Sum of Squares is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2897. Apply Operations on Array to Maximize Sum of Squares?
LeetCode 2897. Apply Operations on Array to Maximize Sum of Squares is rated Hard on LeetCode.
What is the time complexity of LeetCode 2897. Apply Operations on Array to Maximize Sum of Squares?
The Python solution on this page runs in O(n \times \log M).
What is the space complexity of LeetCode 2897. Apply Operations on Array to Maximize Sum of Squares?
The Python solution on this page uses O(\log M) auxiliary space.
What topics does LeetCode 2897. Apply Operations on Array to Maximize Sum of Squares cover?
LeetCode 2897. Apply Operations on Array to Maximize Sum of Squares is tagged Greedy, Bit Manipulation, Array and Hash Table on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview