[LeetCode] Minimum Array Changes to Make Differences Equal

3224. Minimum Array Changes to Make Differences Equal

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:

  • There exists an integer X such that abs(a[i] - a[n - i - 1]) = X for all (0 <= i < n).

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

class Solution {
public:
int minChanges(vector<int>& A, int k) {
vector<int> pre(k + 100);
int n = A.size();
for(int i = 0; i < n / 2; i++) {
int a = A[i], b = A[n-i-1];
if(a < b) swap(a,b);
int x = k - a, y = b;
if(x < y) swap(x,y);
pre[0] += 1;
pre[a-b] -= 1;
pre[a-b+1] += 1;
pre[a-b+x+1] += 1;
}
int res = pre[0];
for(int i = 1; i <= k; i++) {
pre[i] += pre[i-1];
res = min(res, pre[i]);
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2024/07/21/PS/LeetCode/minimum-array-changes-to-make-differences-equal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.