Saturday, 16 Oct 2021

# Minimize increments required to make differences between all pairs of array elements even

Minimize increments required to make differences between all pairs of array elements even
Given an array, arr[] consisting of N integers, the task is to minimize the number of increments of array elements required to make all differences pairs of array elements even.
Examples:

Input: arr[] = {4, 1, 2}Output: 1Explanation:
Operation 1: Increment arr by 1. The array arr[] modifies to {4, 2, 2}.All pairs: (4, 2) → difference = 2(4, 2) → difference = 2(2, 2) → difference = 0Now, the pairwise differences between array elements is even. Hence, the answer is 1.
Input: arr[] = {2, 4}Output: 0Explanation: Differences between all pairs of array elements is already even. Therefore, the answer is 0.

Approach: The given problem can be solved by observing the fact that, to make the difference between all pairs of array elements even, both the elements must be of the same parity. Therefore, the idea is to convert all the array elements to either even numbers or odd numbers. The minimum number of increments is equal to the minimum of the count of even and odd array elements.
Below is the implementation of the above approach:

C++

#include
using namespace std;

void minimumOperations(int arr[], int N)
{

int oddCnt = 0, evenCnt = 0;

for (int i = 0; i < N; i++) {            if (arr[i] % 2 == 0) {                             evenCnt++;         }         else {                             oddCnt++;         }     }                  cout