Make all array elements even by replacing any pair of array elements with their sum
Given an array arr[] consisting of N positive integers, the task is to make all array elements even by replacing any pair of array elements with their sum.
Examples:
Input: arr[] = {5, 6, 3, 7, 20}
Output: 3
Explanation:
Operation 1: Replace arr[0] and arr[2] by their sum ( = 5 + 3 = 8) modifies arr[] to {8, 6, 8, 7, 20}.
Operation 2: Replace arr[2] and arr[3] by their sum ( = 7 + 8 = 15) modifies arr[] to {8, 6, 15, 15, 20}.
Operation 3: Replace arr[2] and arr[3] by their sum ( = 15 + 15 = 30) modifies arr[] to {8, 6, 30, 30, 20}.
Input: arr[] = {2, 4, 16, 8, 7, 9, 3, 1}
Output: 2
Approach: The idea is to keep replacing two odd array elements by their sum until all array elements are even. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void minMoves( int arr[], int N)
{
int odd_element_cnt = 0;
for ( int i = 0; i < N; i++) {
if (arr[i] % 2 != 0) {
odd_element_cnt++;
}
}
int moves = (odd_element_cnt) / 2;
if (odd_element_cnt % 2 != 0)
moves += 2;
cout << moves;
}
int main()
{
int arr[] = { 5, 6, 3, 7, 20 };
int N = sizeof (arr) / sizeof (arr[0]);
minMoves(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void minMoves( int arr[], int N)
{
int odd_element_cnt = 0 ;
for ( int i = 0 ; i < N; i++)
{
if (arr[i] % 2 != 0 )
{
odd_element_cnt++;
}
}
int moves = (odd_element_cnt) / 2 ;
if (odd_element_cnt % 2 != 0 )
moves += 2 ;
System.out.print(moves);
}
public static void main(String[] args)
{
int arr[] = { 5 , 6 , 3 , 7 , 20 };
int N = arr.length;
minMoves(arr, N);
}
}
|
C#
using System;
public class GFG
{
static void minMoves( int []arr, int N)
{
int odd_element_cnt = 0;
for ( int i = 0; i < N; i++)
{
if (arr[i] % 2 != 0)
{
odd_element_cnt++;
}
}
int moves = (odd_element_cnt) / 2;
if (odd_element_cnt % 2 != 0)
moves += 2;
Console.Write(moves);
}
public static void Main(String[] args)
{
int []arr = { 5, 6, 3, 7, 20 };
int N = arr.Length;
minMoves(arr, N);
}
}
|
Python3
def minMoves(arr, N):
odd_element_cnt = 0 ;
for i in range (N):
if (arr[i] % 2 ! = 0 ):
odd_element_cnt + = 1 ;
moves = (odd_element_cnt) / / 2 ;
if (odd_element_cnt % 2 ! = 0 ):
moves + = 2 ;
print (moves);
if __name__ = = '__main__' :
arr = [ 5 , 6 , 3 , 7 , 20 ];
N = len (arr);
minMoves(arr, N);
|
Javascript
<script>
function minMoves(arr, N)
{
var odd_element_cnt = 0;
var i;
for (i = 0; i < N; i++) {
if (arr[i] % 2 != 0) {
odd_element_cnt++;
}
}
var moves = Math.floor((odd_element_cnt)/2);
if (odd_element_cnt % 2 != 0)
moves += 2;
document.write(moves);
}
var arr = [5, 6, 3, 7, 20];
N = arr.length;
minMoves(arr, N);
</script>
|
Time complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
28 Feb, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...