3224. Minimum Array Changes to Make Differences Equal
Problem Statement
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 thatabs(a[i] - a[n - i - 1]) = X
for 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 isnums = [1,
2
,1,2,4,3]
.Replace
nums[3]
by 3. The resulting array isnums = [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 isnums = [0,1,2,
0
,3,6,5,4]
.Replace
nums[4]
by 4. The resulting array isnums = [0,1,2,0,
4
,6,5,4]
.
The integer X
will be 4.
Constraints:
2 <= n == nums.length <= 105
n
is even.0 <= nums[i] <= k <= 105
Intuition
Approach:
Keep track of actual difference -> Zero changes
Also keep track of Maximum achievable difference, that can be formed by changing
element
Now, If we get Max achievable diff for certain pair as 4, then we can acheieve
a diff of 3 2 1 0 All
So
Next step
For finding answer
Take Diff = 18
One Diff(18) to get - Zero_changes to get 18 = Only those extra pairs we need
To change by updating one value in a pair
And remaining goes to 2 Pair
Links
https://leetcode.com/problems/minimum-array-changes-to-make-differences-equal/
Video Links
https://www.youtube.com/watch?v=l5ofGDgIDgE&ab_channel=AryanMittal
Approach 1:
class Solution {
public:
int minChanges(vector<int>& nums, int k) {
int n = nums.size();
unordered_map<int, int> curDiff;
vector<int> one_diff(k+1, 0);
for(int i=0; i<n/2; i++){
int diff = abs(nums[i] - nums[n-i-1]);
curDiff[diff] ++;
int mini = min(nums[i], nums[n-i-1]);
int maxi = max(nums[i], nums[n-i-1]);
int max_diff = max(k-mini, maxi-0);
one_diff[max_diff] ++;
}
// Propogate values
for(int i=k-1; i>=0; i--){
one_diff[i] += one_diff[i+1];
}
//find_ans
int ans = INT_MAX;
for(auto &[diff, count]: curDiff){
int one_extra = one_diff[diff] - count;
int two = n/2 - one_extra - count;
ans = min(ans, one_extra + two*2);
}
return ans;
}
};
Approach 2:
Approach 3:
Approach 4:
Similar Problems
Last updated