Maximum count of equal numbers in an array after performing given operations
Last Updated :
07 Sep, 2022
Given an array of integers. The task is to find the maximum count of equal numbers in an array after applying the given operation any number of times.
In an operation:
- Choose two elements of the array a[i], a[j] (such that i is not equals to j) and,
- Increase number a[i] by 1 and decrease number a[j] by 1 i.e., a[i] = a[i] + 1 and a[j] = a[j] – 1.
Examples:
Input: a = { 1, 4, 1 }
Output: 3
after first step { 1, 3, 2}
after second step { 2, 2, 2}
Input: a = { 1, 2 }
Output: 1
Approach :
- Calculate the sum of the array elements.
- If the sum is divisible by n, where n is the number of elements in the array then the answer will also be n.
- Otherwise, the answer will be n-1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int EqualNumbers( int a[], int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
sum += a[i];
if (sum % n)
return n - 1;
return n;
}
int main()
{
int a[] = { 1, 4, 1 };
int n = sizeof (a) / sizeof (a[0]);
cout << EqualNumbers(a, n);
return 0;
}
|
C
#include <stdio.h>
int EqualNumbers( int a[], int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
sum += a[i];
if (sum % n)
return n - 1;
return n;
}
int main()
{
int a[] = { 1, 4, 1 };
int n = sizeof (a) / sizeof (a[0]);
printf ( "%d\n" , EqualNumbers(a, n));
return 0;
}
|
Java
public class GFG{
static int EqualNumbers( int a[], int n)
{
int sum = 0 ;
for ( int i = 0 ; i < n; i++)
sum += a[i];
if (sum % n != 0 )
return n - 1 ;
return n;
}
public static void main(String args[])
{
int a[] = { 1 , 4 , 1 };
int n = a.length;
System.out.println(EqualNumbers(a, n));
}
}
|
Python3
def EqualNumbers(a, n):
sum = 0 ;
for i in range (n):
sum + = a[i];
if ( sum % n):
return n - 1 ;
return n;
a = [ 1 , 4 , 1 ];
n = len (a);
print (EqualNumbers(a, n));
|
C#
using System;
class GFG
{
static int EqualNumbers( int []a, int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
sum += a[i];
if (sum % n != 0)
return n - 1;
return n;
}
static public void Main ()
{
int []a = { 1, 4, 1 };
int n = a.Length;
Console.WriteLine(EqualNumbers(a, n));
}
}
|
PHP
<?php
function EqualNumbers( $a , $n )
{
$sum = 0;
for ( $i = 0; $i < $n ; $i ++)
$sum += $a [ $i ];
if ( $sum % $n )
return $n - 1;
return $n ;
}
$a = array (1, 4, 1 );
$n = sizeof( $a );
echo EqualNumbers( $a , $n );
|
Javascript
<script>
function EqualNumbers(a, n)
{
let sum = 0;
for (let i = 0; i < n; i++)
sum += a[i];
if (sum % n)
return n - 1;
return n;
}
let a = [ 1, 4, 1 ];
let n = a.length;
document.write(EqualNumbers(a, n));
</script>
|
Complexity Analysis:
- Time Complexity: O(n), where n represents the size of the given array.
- Auxiliary complexity: O(1), no extra space is required, so it is a constant.
Share your thoughts in the comments
Please Login to comment...