Minimum Array Changes to Make Differences Equal Problem
Description
LeetCode Problem 3224.
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
Xsuch thatabs(a[i] - a[n - i - 1]) = Xfor all(0 <= i < n).
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:
- Replace nums[1] by 2. The resulting array is nums = [1,2,1,2,4,3].
- Replace nums[3] by 3. The resulting array is nums = [1,2,1,3,4,3].
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:
- Replace nums[3] by 0. The resulting array is nums = [0,1,2,0,3,6,5,4].
- Replace nums[4] by 4. The resulting array is nums = [0,1,2,0,4,6,5,4].
The integer X will be 4.
Constraints:
2 <= n == nums.length <= 10^5nis even.0 <= nums[i] <= k <= 10^5
Solution
Approach: Difference Array
Suppose that in the final array every pair nums[i], nums[n-1-i] must have absolute difference s. For a pair, let x be the smaller and y the larger value. Then:
- no change is needed if
s = y - x; - one change suffices if
s <= max(y, k - x)(setxto 0 orytok, whichever reaches further); - otherwise two changes are needed.
So for s in [0, y-x-1] the cost is 1, at s = y-x it is 0, in [y-x+1, max(y, k-x)] it is 1, and in [max(y, k-x)+1, k] it is 2. Add these ranges for every pair with a difference array, take prefix sums to get the cost for each s, and return the minimum.
Complexity: time O(n + k), space O(k).
from itertools import accumulate
class Solution:
def minChanges(self, nums: List[int], k: int) -> int:
d = [0] * (k + 2)
n = len(nums)
for i in range(n // 2):
x, y = nums[i], nums[-i - 1]
if x > y:
x, y = y, x
d[0] += 1
d[y - x] -= 1
d[y - x + 1] += 1
d[max(y, k - x) + 1] -= 1
d[max(y, k - x) + 1] += 2
return min(accumulate(d))