给定一个由N个整数组成的数组,任务是找到使数组中的所有元素相等所需的操作数。在一个操作中,我们可以从最大元素到其余数组元素分配相等的权重。如果执行上述操作后无法使数组元素相等,则打印-1。
例子:
Input: arr = [1, 6, 1, 1, 1];
Output: 4
Explanation: Since arr becomes [2, 2, 2, 2, 2] after distribution from max element.
Input : arr = [2, 2, 3];
Output : -1
Explanation: Here arr becomes [3, 3, 1] after distribution.
算法:
- 声明临时变量以存储执行操作的次数。
- 查找给定数组的最大元素并存储其索引值。
- 减去n后,检查所有元素是否等于最大元素。
- 再次检查每个元素是否等于其他元素,然后返回n。
下面是上述方法的实现:
C++
// C++ program to find the number
//of operations required to make
//all array elements Equal
#include
using namespace std;
//Function to find maximum
//element of the given array
int find_n(int a[],int n)
{
int j = 0, k = 0, s = 0;
int x = *max_element(a, a + n);
int y = *min_element(a, a + n);
for (int i = 0; i < n; i++)
{
if (a[i] == x)
{
s = i;
break;
}
}
for (int i =0;i
Java
// Java program to find the number
//of operations required to make
//all array elements Equal
import java.util.Arrays;
class GFG {
//Function to find maximum
//element of the given array
static int find_n(int[] a) {
int j = 0, k = 0, s = 0;
int x = Arrays.stream(a).max().getAsInt();
int y = Arrays.stream(a).min().getAsInt();
for (int i : a) {
if (a[i] == x) {
s = i;
break;
}
}
for (int i : a) {
if (i != x && i <= y && i != 0) {
a[j] += 1;
a[s] -= 1;
x -= 1;
k += 1;
j += 1;
} else if (i != 0) {
j += 1;
}
}
for (int i : a) {
if (a[i] != x) {
k = -1;
break;
}
}
return k;
}
//Driver Code
public static void main(String[] args) {
int[] a = {1, 6, 1, 1, 1};
System.out.println(find_n(a));
}
}
Python3
# Python program to find the number
# of operations required to make
# all array elements Equal
# Function to find maximum
# element of the given array
def find_n(a):
j, k = 0, 0
x = max(a)
for i in range(len(a)):
if(a[i] == x):
s = i
break
for i in a:
if(i != x and i <= min(a) and i !='\0'):
a[j] += 1
a[s] -= 1
x -= 1
k += 1
j += 1
elif(i != '\0'):
j += 1
for i in range(len(a)):
if(a[i] != x):
k = -1
break
return k
# Driver Code
a = [1, 6, 1, 1, 1]
print (find_n(a))
C#
// C# program to find the number
// of operations required to make
// all array elements Equal
using System;
using System.Linq;
class GFG
{
// Function to find maximum
// element of the given array
static int find_n(int []a)
{
int j = 0, k = 0, s = 0;
int x = a.Max();
int y = a.Min();
foreach(int i in a)
{
if (a[i] == x)
{
s = i;
break;
}
}
foreach (int i in a)
{
if (i != x && i <= y && i != 0)
{
a[j] += 1;
a[s] -= 1;
x -= 1;
k += 1;
j += 1;
}
else if (i != 0)
{
j += 1;
}
}
foreach (int i in a)
{
if (a[i] != x)
{
k = -1;
break;
}
}
return k;
}
// Driver Code
public static void Main()
{
int[] a = {1, 6, 1, 1, 1};
Console.Write(find_n(a));
}
}
// This code contributed by 29AjayKumar
PHP
Javascript
输出:
4
时间复杂度:O(n)
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。