LeetCode in Kotlin

3806. Maximum Bitwise AND After Increment Operations

Hard

You are given an integer array nums and two integers k and m.

You may perform at most k operations. In one operation, you may choose any index i and increase nums[i] by 1.

Return an integer denoting the maximum possible bitwise AND of any subset of size m after performing up to k operations optimally.

Example 1:

Input: nums = [3,1,2], k = 8, m = 2

Output: 6

Explanation:

Example 2:

Input: nums = [1,2,8,4], k = 7, m = 3

Output: 4

Explanation:

Example 3:

Input: nums = [1,1], k = 3, m = 2

Output: 2

Explanation:

Constraints:

Solution

class Solution {
    fun maximumAND(a: IntArray, b: Int, c: Int): Int {
        var e: Long = 0L
        val f = a.size
        val g = LongArray(f)
        for (h in 30 downTo 0) {
            val i = e or (1L shl h)
            for (j in 0..<f) {
                val k = a[j].toLong()
                val l = i and k.inv()
                if (l == 0L) {
                    g[j] = 0
                } else {
                    var n = 63 - java.lang.Long.numberOfLeadingZeros(l)
                    while (((k shr n) and 1L) == 1L) {
                        n++
                    }
                    val o = (1L shl n) - 1
                    g[j] = ((k and o.inv()) or (1L shl n) or (i and o)) - k
                }
            }
            g.sort()
            var p: Long = 0
            for (q in 0..<c) {
                p += g[q]
            }
            if (p <= b) {
                e = i
            }
        }
        return e.toInt()
    }
}