给定一个整数数组。任务是在多次应用给定操作后,在数组中找到最大数目的相等计数。
在操作中:
1. Choose two elements of the array a[i], a[j] (such that i is not equals to j) and,
2. 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.
例子:
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
方法 :
- 计算数组元素的总和。
- 如果总和可被n整除,其中n是数组中元素的数量,则答案也将为n。
- 否则,答案将为n-1。
下面是上述方法的实现:
C++
// CPP program to find the maximum
// number of equal numbers in an array
#include
using namespace std;
// Function to find the maximum number of
// equal numbers in an array
int EqualNumbers(int a[], int n)
{
// to store sum of elements
int sum = 0;
for (int i = 0; i < n; i++)
sum += a[i];
// if sum of numbers is not divisible
// by n
if (sum % n)
return n - 1;
return n;
}
// Driver Code
int main()
{
int a[] = { 1, 4, 1 };
// size of an array
int n = sizeof(a) / sizeof(a[0]);
cout << EqualNumbers(a, n);
return 0;
}
Java
// Java program to find the maximum
// number of equal numbers in an array
public class GFG{
// Function to find the maximum number of
// equal numbers in an array
static int EqualNumbers(int a[], int n)
{
// to store sum of elements
int sum = 0;
for (int i = 0; i < n; i++)
sum += a[i];
// if sum of numbers is not divisible
// by n
if (sum % n != 0)
return n - 1;
return n;
}
// Driver code
public static void main(String args[])
{
int a[] = { 1, 4, 1 };
// size of an array
int n = a.length;
System.out.println(EqualNumbers(a, n));
}
// This code is contributed by ANKITRAI1
}
Python3
# Python3 program to find the maximum
# number of equal numbers in an array
# Function to find the maximum
# number of equal numbers in an array
def EqualNumbers(a, n):
# to store sum of elements
sum = 0;
for i in range(n):
sum += a[i];
# if sum of numbers is not
# divisible by n
if (sum % n):
return n - 1;
return n;
# Driver Code
a = [1, 4, 1 ];
# size of an array
n = len(a);
print(EqualNumbers(a, n));
# This code is contributed by mits
C#
// C# program to find the maximum
// number of equal numbers in an array
using System;
class GFG
{
// Function to find the maximum
// number of equal numbers in an array
static int EqualNumbers(int []a, int n)
{
// to store sum of elements
int sum = 0;
for (int i = 0; i < n; i++)
sum += a[i];
// if sum of numbers is not
// divisible by n
if (sum % n != 0)
return n - 1;
return n;
}
// Driver code
static public void Main ()
{
int []a = { 1, 4, 1 };
// size of an array
int n = a.Length;
Console.WriteLine(EqualNumbers(a, n));
}
}
// This code is contributed by jit_t
PHP
Javascript
输出:
3