给定一个数组, arr []由N个整数组成,任务是最小化使所有差值对偶数成对所需的数组元素的增量数量。
例子:
Input: arr[] = {4, 1, 2}
Output: 1
Explanation:
Operation 1: Increment arr[1] by 1. The array arr[] modifies to {4, 2, 2}.
All pairs: (4, 2) → difference = 2
(4, 2) → difference = 2
(2, 2) → difference = 0
Now, the pairwise differences between array elements is even. Hence, the answer is 1.
Input: arr[] = {2, 4}
Output: 0
Explanation: Differences between all pairs of array elements is already even. Therefore, the answer is 0.
方法:可以通过观察以下事实来解决给定的问题:为了使所有成对的数组元素之间的差异均匀,两个元素必须具有相同的奇偶性。因此,我们的想法是将所有数组元素都转换为偶数或奇数。最小增量数等于偶数和奇数数组元素的计数的最小值。
下面是上述方法的实现:
C++
Java
Python3
C#
输出:
时间复杂度: O(N)
辅助空间: O(1)