Back to October Back to Year 2026
HARD 12 Oct 2026 View on LeetCode

2897. Apply Operations on Array to Maximize Sum of Squares

</> Solution

/**
 * Problem: LeetCode 2897 - Apply Operations on Array to Maximize Sum of Squares
 * Difficulty: Hard
 * Language: Java
 * Author: CodeByTushu
 */
import java.util.List;

/**
 * Problem: LeetCode 2897 - Apply Operations on Array to Maximize Sum of Squares
 * Difficulty: Hard
 * Language: Java
 * Author: CodeByTushu
 */
class Solution {
    public int maxSum(List<Integer> nums, int k) {
        final int MOD = 1_000_000_007;
        int[] cnt = new int[30];
        for (int num : nums) {
            for (int b = 0; b < 30; b++) {
                if (((num >> b) & 1) == 1) cnt[b]++;
            }
        }
        long ans = 0;
        for (int i = 0; i < k; i++) {
            long cur = 0;
            for (int b = 0; b < 30; b++) {
                if (cnt[b] > 0) {
                    cur |= (1L << b);
                    cnt[b]--;
                }
            }
            ans = (ans + (cur % MOD) * (cur % MOD)) % MOD;
        }
        return (int) ans;
    }
}

TIME COMPLEXITY

O(N + K) where N = nums.length, K = k

SPACE COMPLEXITY

O(1)

TOPICS

Array Bit Manipulation Greedy Hash Table Math