给定一个由N个整数组成的数组arr [] ,任务是找到需要递增的最小数量的数组元素,以使所有成对连续元素之间的绝对差为偶数。
例子:
Input: arr[] = {2, 4, 3, 1, 8}
Output: 2
Explanation:
Operation 1: Incrementing the array element arr[2](= 3) modifies the array to {2, 4, 4, 1, 8}.
Operation 2: Incrementing the array element arr[3](= 1) modifies the array to {2, 4, 4, 2, 8}.
Therefore, the difference between all pairwise adjacent array elements is even.
Input: arr[] = {1, 3, 5, 2}
Output: 1
方法:可以使用以下事实来解决给定的问题:两个数字之间的差异是偶数,并且仅当两个数字都是奇数或偶数时才可解决。因此,其思想是使两个数字均为偶数的所有奇数或偶数都递增,并且对于最小的递增计数,应打印出奇数或偶数的最小值。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the minimum number
// of increments of array elements
// required to make difference between
// all pairwise adjacent elements even
int minOperations(int arr[], int n)
{
// Stores the count of
// odd and even elements
int oddcount = 0, evencount = 0;
// Traverse the array
for (int i = 0; i < n; i++) {
// Increment odd count
if (arr[i] % 2 == 1)
oddcount++;
// Increment even count
else
evencount++;
}
// Return the minimum number
// of operations required
return min(oddcount, evencount);
}
// Driver Code
int main()
{
int arr[] = { 2, 4, 3, 1, 8 };
int N = sizeof(arr) / sizeof(arr[0]);
cout << minOperations(arr, N);
return 0;
}
输出:
2
时间复杂度: O(N)
辅助空间: O(N)