LeetCode in Kotlin

2897. Apply Operations on Array to Maximize Sum of Squares

Hard

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:

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:

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:

Solution

class Solution {
    fun maxSum(nums: List<Int>, k: Int): Int {
        val bits = IntArray(32)
        for (n in nums) {
            for (i in 0..31) {
                bits[i] += (n shr i) and 1
            }
        }
        val mod = 1000000007
        var sum: Long = 0
        for (i in 0 until k) {
            var n: Long = 0
            for (j in 0..31) {
                if (bits[j] > i) {
                    n = n or (1 shl j).toLong()
                }
            }
            sum = (sum + n * n % mod) % mod
        }
        return sum.toInt()
    }
}