Maximum possible elements which are divisible by 2
Given an integer array arr of size N. The task is to find the maximum possible elements in the array which are divisible by 2 after modifying the array. One can perform the below operation an arbitrary number of times(possibly zero times).
Replace any two elements in the array with their sum.
Examples:
Input : arr = [1, 2, 3, 1, 3]
Output : 3
After adding elements at index 0 and 2, and index 3 and 4, array becomes arr=[4, 2, 4].
Input : arr = [1, 2, 3, 4, 5]
Output : 3
After adding 1 and 3, array becomes arr=[4, 2, 4, 5].
Approach :
First, observation is that we don’t need to modify elements that are divisible by 2(i.e., even numbers). Then we left with odd numbers. The addition of two numbers will give an even number that is divisible by 2.
So finally, the result will be:
count_even + count_odd/2.
Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
int Divisible( int arr[], int n)
{
int count_even = 0;
for ( int i = 0; i < n; i++)
if (arr[i] % 2 == 0)
count_even++;
return count_even + (n - count_even) / 2;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << Divisible(arr, n);
return 0;
}
|
Java
class GFG
{
static int Divisible( int arr[], int n)
{
int count_even = 0 ;
for ( int i = 0 ; i < n; i++)
if (arr[i] % 2 == 0 )
count_even++;
return count_even + (n - count_even) / 2 ;
}
public static void main (String[] args)
{
int arr[] = { 1 , 2 , 3 , 4 , 5 };
int n = arr.length;
System.out.println(Divisible(arr, n));
}
}
|
Python3
def Divisible(arr, n):
count_even = 0
for i in range (n):
if (arr[i] % 2 = = 0 ):
count_even + = 1
return count_even + (n - count_even) / / 2
arr = [ 1 , 2 , 3 , 4 , 5 ]
n = len (arr)
print (Divisible(arr, n))
|
C#
using System;
class GFG
{
static int Divisible( int []arr, int n)
{
int count_even = 0;
for ( int i = 0; i < n; i++)
if (arr[i] % 2 == 0)
count_even++;
return count_even + (n - count_even) / 2;
}
static public void Main ()
{
int []arr = { 1, 2, 3, 4, 5 };
int n = arr.Length;
Console.Write(Divisible(arr, n));
}
}
|
Javascript
<script>
function Divisible(arr, n)
{
let count_even = 0;
for (let i = 0; i < n; i++)
if (arr[i] % 2 == 0)
count_even++;
return count_even + parseInt((n - count_even) / 2);
}
let arr = [ 1, 2, 3, 4, 5 ];
let n = arr.length;
document.write(Divisible(arr, n));
</script>
|
Time complexity: O(N).
Auxiliary Space: O(1).
Last Updated :
09 Feb, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...