Apply Operations on Array to Maximize Sum of Squares — LeetCode 2897 Python Solution
- Problem
- #2897
- Pattern
- Bit Manipulation
- Reading time
- 4 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log M) |
| Space | O(\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.