Given an array arr[] consisting of N integers, the task is to find the minimum number of array elements required to be incremented to make the absolute difference between all pairwise consecutive elements even.
Examples:
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
Approach: The given problem can be solved by using the fact that the difference between two numbers is even if and only if both numbers are odd or even. Therefore, the idea is to increase either all the odd or even numbers. Both numbers are even and, for the minimum count of increment, print the minimum of the count of odd numbers or count of even numbers is a result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minOperations( int arr[], int n)
{
int oddcount = 0, evencount = 0;
for ( int i = 0; i < n; i++) {
if (arr[i] % 2 == 1)
oddcount++;
else
evencount++;
}
return min(oddcount, evencount);
}
int main()
{
int arr[] = { 2, 4, 3, 1, 8 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << minOperations(arr, N);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
class GFG{
static int minOperations( int arr[], int n)
{
int oddcount = 0 , evencount = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (arr[i] % 2 == 1 )
oddcount++;
else
evencount++;
}
return Math.min(oddcount, evencount);
}
public static void main (String[] args)
{
int arr[] = { 2 , 4 , 3 , 1 , 8 };
int N = arr.length;
System.out.println(minOperations(arr, N));
}
}
|
Python3
def minOperations(arr, n):
oddcount, evencount = 0 , 0
for i in range (n):
if (arr[i] % 2 = = 1 ):
oddcount + = 1
else :
evencount + = 1
return min (oddcount, evencount)
if __name__ = = '__main__' :
arr = [ 2 , 4 , 3 , 1 , 8 ]
N = len (arr)
print (minOperations(arr, N))
|
C#
using System;
class GFG {
static int minOperations( int [] arr, int n)
{
int oddcount = 0, evencount = 0;
for ( int i = 0; i < n; i++) {
if (arr[i] % 2 == 1)
oddcount++;
else
evencount++;
}
return Math.Min(oddcount, evencount);
}
public static void Main()
{
int [] arr = { 2, 4, 3, 1, 8 };
int N = (arr.Length);
Console.WriteLine(minOperations(arr, N));
}
}
|
Javascript
<script>
function minOperations(arr, n)
{
var oddcount = 0, evencount = 0;
for ( var i = 0; i < n; i++)
{
if (arr[i] % 2 == 1)
oddcount++;
else
evencount++;
}
return Math.min(oddcount, evencount);
}
var arr = [ 2, 4, 3, 1, 8 ];
var N = arr.length;
document.write(minOperations(arr, N));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)