LeetCode-in-Java

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

public class Solution {
    public int minOperations(int[] nums, int k) {
        int[] even = new int[k];
        int[] odd = new int[k];
        for (int i = 0; i < nums.length; i++) {
            int rem = nums[i] % k;
            for (int j = 0; j < k; j++) {
                int diff = Math.abs(rem - j);
                int cost = Math.min(diff, k - diff);
                if (i % 2 == 0) {
                    even[j] += cost;
                } else {
                    odd[j] += cost;
                }
            }
        }
        int ans = Integer.MAX_VALUE;
        for (int x = 0; x < k; x++) {
            for (int y = 0; y < k; y++) {
                if (x != y) {
                    ans = Math.min(ans, odd[x] + even[y]);
                }
            }
        }
        return ans;
    }
}