LeetCode-in-Java

3224. Minimum Array Changes to Make Differences Equal

Medium

You are given an integer array nums of size n where n is even, and an integer k.

You can perform some changes on the array, where in one change you can replace any element in the array with any integer in the range from 0 to k.

You need to perform some changes (possibly none) such that the final array satisfies the following condition:

Return the minimum number of changes required to satisfy the above condition.

Example 1:

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

Output: 2

Explanation:
We can perform the following changes:

The integer X will be 2.

Example 2:

Input: nums = [0,1,2,3,3,6,5,4], k = 6

Output: 2

Explanation:
We can perform the following operations:

The integer X will be 4.

Constraints:

Solution

public class Solution {
    public int minChanges(int[] nums, int k) {
        int[] cm = new int[k + 2];
        for (int i = 0; i < nums.length / 2; i++) {
            int a = Math.min(nums[i], nums[nums.length - 1 - i]);
            int b = Math.max(nums[i], nums[nums.length - 1 - i]);
            int d = b - a;
            if (d > 0) {
                cm[0]++;
                cm[d]--;
                cm[d + 1]++;
                int max = Math.max(a, k - b) + d;
                cm[max + 1]++;
            } else {
                cm[1]++;
                int max = Math.max(a, k - a);
                cm[max + 1]++;
            }
        }
        int sum = cm[0];
        int res = cm[0];
        for (int i = 1; i <= k; i++) {
            sum += cm[i];
            res = Math.min(res, sum);
        }
        return res;
    }
}