2017网易内推笔试题

时间:2021-09-13 13:49:32

题目:有n个奶牛排成一排,每个奶牛拥有一定的苹果数ai,每次操作可以从任一只奶牛手中仅且拿2个两个苹果给另外一只奶牛,输出至少要操作多少次才能使得所有奶牛的苹果数相等,如果不可能达到相等状态,则输出-1.
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner cin = new Scanner(System.in);
while(cin.hasNextLine()){

       int n = Integer.valueOf(cin.nextLine());
int[] arr = new int[n];
String[] str = cin.nextLine().split(" ");
int sum = 0;
for(int i=0;i<n;i++){
arr[i] = Integer.valueOf(str[i]);
sum+=arr[i];
}
if(sum%n!=0){
System.out.println(-1);continue;
}
int per = sum/n;
int count = 0;
boolean flag = true;
for(int i=0;i<n;i++){
int yiDong = Math.abs(arr[i]-per);
if( yiDong%2!=0){
System.out.println(-1);
flag =false;
break;
}
count = count + yiDong/2;
}
if(flag){
System.out.print(count/2);
}
}

}
}