Minimum elements to be removed such that sum of adjacent elements is always even
Given an array of N integers. The task is to eliminate the minimum number of elements such that in the resulting array the sum of any two adjacent values is even.
Examples:
Input : arr[] = {1, 2, 3}
Output : 1
Remove 2 from the array.
Input : arr[] = {1, 3, 5, 4, 2}
Output : 2
Remove 4 and 2.
Approach: The sum of 2 numbers is even if either both of them is odd or both of them is even. This means for every pair of consecutive numbers that have the different parity, eliminate one of them.
So, to make the adjacent elements sum even, either all elements should be odd or even. So the following greedy algorithm works:
- Go through all the elements in order.
- Count the odd and even elements in the array.
- Return the minimum count.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int min_elimination( int n, int arr[])
{
int countOdd = 0;
for ( int i = 0; i < n; i++)
if (arr[i] % 2)
countOdd++;
return min(countOdd, n - countOdd);
}
int main()
{
int arr[] = { 1, 2, 3, 7, 9 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << min_elimination(n, arr);
return 0;
}
|
Java
class GFG
{
static int min_elimination( int n, int arr[])
{
int countOdd = 0 ;
for ( int i = 0 ; i < n; i++)
if (arr[i] % 2 == 1 )
countOdd++;
return Math.min(countOdd, n - countOdd);
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 3 , 7 , 9 };
int n = arr.length;
System.out.println(min_elimination(n, arr));
}
}
|
Python3
def min_elimination(n, arr):
countOdd = 0
for i in range (n):
if (arr[i] % 2 ):
countOdd + = 1
return min (countOdd, n - countOdd)
if __name__ = = '__main__' :
arr = [ 1 , 2 , 3 , 7 , 9 ]
n = len (arr)
print (min_elimination(n, arr))
|
C#
using System;
class GFG
{
static int min_elimination( int n, int [] arr)
{
int countOdd = 0;
for ( int i = 0; i < n; i++)
if (arr[i] % 2 == 1)
countOdd++;
return Math.Min(countOdd, n - countOdd);
}
public static void Main()
{
int [] arr = { 1, 2, 3, 7, 9 };
int n = arr.Length;
Console.WriteLine(min_elimination(n, arr));
}
}
|
PHP
<?php
function min_elimination( $n , $arr )
{
$countOdd = 0;
for ( $i = 0; $i < $n ; $i ++)
if ( $arr [ $i ] % 2 == 1)
$countOdd ++;
return min( $countOdd , $n - $countOdd );
}
$arr = array (1, 2, 3, 7, 9);
$n = sizeof( $arr );
echo (min_elimination( $n , $arr ));
?>
|
Javascript
<script>
function min_elimination(n, arr)
{
let countOdd = 0;
for (let i = 0; i < n; i++)
if (arr[i] % 2)
countOdd++;
return Math.min(countOdd, n - countOdd);
}
let arr= [1, 2, 3, 7, 9];
let n = arr.length;
document.write(min_elimination(n, arr));
</script>
|
Time Complexity: O(N )
Auxiliary Space: O(1)
Last Updated :
15 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...