fork download
  1. /* package whatever; // don't place package name! */
  2. import java.util.*;
  3. import java.lang.*;
  4.  
  5. class spoj
  6. {
  7. // this method takes number of packets in count variable and number of candies in each packet in input array.
  8. void calculateMoves(int packet,int input[]){
  9.  
  10.  
  11. int sum=0;
  12. int candyPerPack=0;
  13. int moves=0;
  14. int j=0;
  15.  
  16. // sum all the candies available in each packet
  17. for(j=0;j<packet;j++){
  18. sum=sum+input[j];
  19. }
  20.  
  21. // check whether the sum can be divided by number of packets or not.
  22. // if not then print -1.
  23. // else count how many candies need to be moved.
  24. if((sum%packet)!=0){
  25. System.out.println("-1");
  26. }
  27. else{
  28. candyPerPack=sum/packet;
  29. for(j=0;j<packet;j++){
  30. if(input[j]<candyPerPack){
  31. moves=moves+(candyPerPack-input[j]);
  32. }
  33.  
  34. }
  35.  
  36. System.out.println(moves);
  37. }
  38.  
  39.  
  40. }
  41.  
  42. public static void main (String[] args) throws java.lang.Exception
  43. {
  44.  
  45.  
  46. int input[]=new int[1000];
  47. Scanner s=new Scanner(System.in);
  48. int count=0;
  49. spoj sp=new spoj();
  50.  
  51. int i=0,j=0;
  52. int temp=0;
  53.  
  54. while(s.hasNext()){
  55. count=s.nextInt();
  56. if(count==-1){
  57. break;
  58. }
  59.  
  60. i=0;
  61. while(i!=count){
  62. input[i]=s.nextInt();
  63.  
  64.  
  65. i++;
  66. }
  67.  
  68. sp.calculateMoves(count,input);
  69.  
  70.  
  71.  
  72. }
  73.  
  74.  
  75. }
  76. }
Success #stdin #stdout 0.15s 321088KB
stdin
5
1
1
1
1
6
2
3
4
-1
stdout
4
-1