LeetCode in Kotlin

3937. Minimum Operations to Make Array Modulo Alternating I

Medium

You are given an integer array nums and an integer k.

In one operation, you can increase or decrease any element of nums by 1.

An array is called modulo alternating if there exist two distinct integers x and y (0 <= x, y < k) such that:

Return the minimum number of operations required to make nums modulo alternating.

Example 1:

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

Output: 2

Explanation:

Example 2:

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

Output: 1

Explanation:

Constraints:

Solution

import kotlin.math.abs
import kotlin.math.min

class Solution {
    fun minOperations(nums: IntArray, k: Int): Int {
        val even = IntArray(k)
        val odd = IntArray(k)
        for (i in nums.indices) {
            val rem = nums[i] % k
            for (j in 0..<k) {
                val diff = abs(rem - j)
                val cost = min(diff, k - diff)
                if (i % 2 == 0) {
                    even[j] += cost
                } else {
                    odd[j] += cost
                }
            }
        }
        var ans = Int.MAX_VALUE
        for (x in 0..<k) {
            for (y in 0..<k) {
                if (x != y) {
                    ans = min(ans, odd[x] + even[y])
                }
            }
        }
        return ans
    }
}