program answer
  implicit none

  integer :: i, N, m, same, su, cost
  real(8) :: ave
  integer, allocatable :: a(:)
   read(*,*) N
  allocate(a(N))
  read(*,*) a

  same = 0
  do i = 1, N-1
     if(a(i) == a(i+1)) then
        same = same + 1.
     end if
  end do

  if(same==N-1) then
     write(*,*) 0
     stop
  end if

  ave=nint(sum(a)/N*1.0_8)
  
  su = 0
  do i = 1, N
     su = su + a(i)*a(i)
  end do

  cost = N*(ave)*(ave)-2*ave*sum(a)+su
  write(*,*) cost
  deallocate(a)
  stop
 end program answer
