Minimize increments required to make differences between all pairs of array elements even
Last Updated :
15 Feb, 2022
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++
#include <bits/stdc++.h>
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 << min(oddCnt, evenCnt);
}
int main()
{
int arr[] = { 4, 1, 2 };
int N = sizeof (arr) / sizeof (arr[0]);
minimumOperations(arr, N);
return 0;
}
|
Java
public class GFG
{
static 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++;
}
}
System.out.print(Math.min(oddCnt, evenCnt));
}
public static void main(String args[])
{
int [] arr = { 4 , 1 , 2 };
int N = arr.length;
minimumOperations(arr, N);
}
}
|
Python3
def minimumOperations(arr, N) :
oddCnt = 0
evenCnt = 0
for i in range (N):
if (arr[i] % 2 = = 0 ) :
evenCnt + = 1
else :
oddCnt + = 1
print ( min (oddCnt, evenCnt))
arr = [ 4 , 1 , 2 ]
N = len (arr)
minimumOperations(arr, N)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static 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++;
}
}
Console.Write(Math.Min(oddCnt, evenCnt));
}
static void Main()
{
int [] arr = { 4, 1, 2 };
int N = arr.Length;
minimumOperations(arr, N);
}
}
|
Javascript
<script>
function minimumOperations(arr,N)
{
let oddCnt = 0, evenCnt = 0;
for (let i = 0; i < N; i++)
{
if (arr[i] % 2 == 0)
{
evenCnt++;
}
else
{
oddCnt++;
}
}
document.write(Math.min(oddCnt, evenCnt));
}
let arr = [ 4, 1, 2 ];
let N = arr.length;
minimumOperations(arr, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...