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:
i, nums[i] % k == xi, nums[i] % k == yReturn the minimum number of operations required to make nums modulo alternating.
Example 1:
Input: nums = [1,4,2,8], k = 3
Output: 2
Explanation:
x = 1 for even indices and y = 2 for odd indices.nums[1] = 4 by 1, giving nums = [1, 5, 2, 8].nums[2] = 2 by 1, giving nums = [1, 5, 1, 8].nums[i] % k = 1, and for odd indices, nums[i] % k = 2.Example 2:
Input: nums = [1,1,1], k = 3
Output: 1
Explanation:
nums[1] by 1 gives nums = [1, 2, 1], which satisfies the condition with x = 1 and y = 2.Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 1092 <= k <= 100import 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
}
}