You are given two arrays of positive integers, nums and target, of the same length. In one operation you choose two distinct indices i and j and set nums[i] = nums[i] + 2 and nums[j] = nums[j] - 2.
Two arrays are similar when every value occurs the same number of times in both, that is, when one is a rearrangement of the other.
Return the minimum number of operations needed to make nums similar to target. The input guarantees that this is possible.
Function Signature
def min_operations_to_make_similar(nums: list[int], target: list[int]) -> int:
Rules
-
Each operation changes exactly two different positions of
nums
, one by +2 and the other by -2;
target
never changes.
-
Only the multiset of values matters at the end; positions do not have to match.
-
There is no bound on the values during the process; only the final array has to be similar to
target
.
Constraints
-
1 <= n <= 10^5
, where
n = len(nums) = len(target)
-
1 <= nums[i], target[i] <= 10^6
-
nums
can always be made similar to
target
with the operation above.
-
The answer can exceed
2^31 - 1
(it stays below
2.5 * 10^10
); return it as an exact integer.
Examples
Example 1
Input: nums = [9, 4, 3], target = [5, 7, 4]
Output: 1
Adding 2 to the 3 and subtracting 2 from the 9 gives [7, 4, 5], a rearrangement of target.
Example 2
Input: nums = [2, 10, 5], target = [6, 9, 2]
Output: 2
Adding 2 to the 5 and subtracting 2 from the 10 gives [2, 8, 7]; adding 2 to the 7 and subtracting 2 from the 8 gives [2, 6, 9], a rearrangement of target. No single operation is enough.
Example 3
Input: nums = [3, 8], target = [8, 3]
Output: 0
nums is already a rearrangement of target.