Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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:
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]). Here, OR denotes the bitwise OR operation, and AND denotes the bitwise AND operation.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 109 + 7.
Example 1:
Input: nums = [2,6,5,8], k = 2 Output: 261 Explanation: We can do the following operations on the array: - Choose i = 0 and j = 3, then change nums[0] to (2 AND 8) = 0 and nums[3] to (2 OR 8) = 10. The resulting array is nums = [0,6,5,10]. - Choose i = 2 and j = 3, then change nums[2] to (5 AND 10) = 0 and nums[3] to (5 OR 10) = 15. The resulting array is nums = [0,6,0,15]. We can choose the elements 15 and 6 from the final array. The sum of squares is 152 + 62 = 261. It can be shown that this is the maximum value we can get.
Example 2:
Input: nums = [4,5,4,7], k = 3 Output: 90 Explanation: We do not need to apply any operations. We can choose the elements 7, 5, and 4 with a sum of squares: 72 + 52 + 42 = 90. It can be shown that this is the maximum value we can get.
Constraints:
1 <= k <= nums.length <= 1051 <= nums[i] <= 109Problem summary: 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]). Here, OR denotes the bitwise OR operation, and AND denotes the bitwise AND operation. 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 109 + 7.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Greedy · Bit Manipulation
[2,6,5,8] 2
[4,5,4,7] 3
minimize-or-of-remaining-elements-using-operations)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2897: Apply Operations on Array to Maximize Sum of Squares
class Solution {
public int maxSum(List<Integer> nums, int k) {
final int mod = (int) 1e9 + 7;
int[] cnt = new int[31];
for (int x : nums) {
for (int i = 0; i < 31; ++i) {
if ((x >> i & 1) == 1) {
++cnt[i];
}
}
}
long ans = 0;
while (k-- > 0) {
int x = 0;
for (int i = 0; i < 31; ++i) {
if (cnt[i] > 0) {
x |= 1 << i;
--cnt[i];
}
}
ans = (ans + 1L * x * x) % mod;
}
return (int) ans;
}
}
// Accepted solution for LeetCode #2897: Apply Operations on Array to Maximize Sum of Squares
func maxSum(nums []int, k int) (ans int) {
cnt := [31]int{}
for _, x := range nums {
for i := 0; i < 31; i++ {
if x>>i&1 == 1 {
cnt[i]++
}
}
}
const mod int = 1e9 + 7
for ; k > 0; k-- {
x := 0
for i := 0; i < 31; i++ {
if cnt[i] > 0 {
x |= 1 << i
cnt[i]--
}
}
ans = (ans + x*x) % mod
}
return
}
# Accepted solution for LeetCode #2897: Apply Operations on Array to Maximize Sum of Squares
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
// Accepted solution for LeetCode #2897: Apply Operations on Array to Maximize Sum of Squares
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #2897: Apply Operations on Array to Maximize Sum of Squares
// class Solution {
// public int maxSum(List<Integer> nums, int k) {
// final int mod = (int) 1e9 + 7;
// int[] cnt = new int[31];
// for (int x : nums) {
// for (int i = 0; i < 31; ++i) {
// if ((x >> i & 1) == 1) {
// ++cnt[i];
// }
// }
// }
// long ans = 0;
// while (k-- > 0) {
// int x = 0;
// for (int i = 0; i < 31; ++i) {
// if (cnt[i] > 0) {
// x |= 1 << i;
// --cnt[i];
// }
// }
// ans = (ans + 1L * x * x) % mod;
// }
// return (int) ans;
// }
// }
// Accepted solution for LeetCode #2897: Apply Operations on Array to Maximize Sum of Squares
function maxSum(nums: number[], k: number): number {
const cnt: number[] = Array(31).fill(0);
for (const x of nums) {
for (let i = 0; i < 31; ++i) {
if ((x >> i) & 1) {
++cnt[i];
}
}
}
let ans = 0n;
const mod = 1e9 + 7;
while (k-- > 0) {
let x = 0;
for (let i = 0; i < 31; ++i) {
if (cnt[i] > 0) {
x |= 1 << i;
--cnt[i];
}
}
ans = (ans + BigInt(x) * BigInt(x)) % BigInt(mod);
}
return Number(ans);
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.