The Wayback Machine - https://web.archive.org/web/20210219202523/https://www.geeksforgeeks.org/minimize-increments-required-to-make-differences-between-all-pairs-of-array-elements-even/
Skip to content
Related Articles

Related Articles

Minimize increments required to make differences between all pairs of array elements even
  • Last Updated : 19 Feb, 2021

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: 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.



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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the minimum increments
// required to difference between all
// pairs of array elements even
void minimumOperations(int arr[], int N)
{
    // Store the count of odd
    // and even numbers
    int oddCnt = 0, evenCnt = 0;
  
    // Traverse the array
    for (int i = 0; i < N; i++) {
  
        if (arr[i] % 2 == 0) {
  
            // Increment evenCnt by 1
            evenCnt++;
        }
        else {
  
            // Increment eveCnt by 1
            oddCnt++;
        }
    }
  
    // Print the minimum of oddCnt
    // and eveCnt
    cout << min(oddCnt, evenCnt);
}
  
// Driver Code
int main()
{
    int arr[] = { 4, 1, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
    minimumOperations(arr, N);
  
    return 0;
}

chevron_right


Output:

1

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :