In the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are m_{i} tasks assigned to the i-th server.

In order to balance the load for each server, you want to reassign some tasks to make the difference between the most loaded server and the least loaded server as small as possible. In other words you want to minimize expression m_{a} - m_{b}, where a is the most loaded server and b is the least loaded one.

In one second you can reassign a single task. Thus in one second you can choose any pair of servers and move a single task from one server to another.

Write a program to find the minimum number of seconds needed to balance the load of servers.


-----Input-----

The first line contains positive number n (1 ≤ n ≤ 10^5) — the number of the servers. 

The second line contains the sequence of non-negative integers m_1, m_2, ..., m_{n} (0 ≤ m_{i} ≤ 2·10^4), where m_{i} is the number of tasks assigned to the i-th server.


-----Output-----

Print the minimum number of seconds required to balance the load.


-----Examples-----
Input
2
1 6

Output
2

Input
7
10 11 10 11 10 11 11

Output
0

Input
5
1 2 3 4 5

Output
3



-----Note-----

In the first example two seconds are needed. In each second, a single task from server #2 should be moved to server #1. After two seconds there should be 3 tasks on server #1 and 4 tasks on server #2.

In the second example the load is already balanced.

A possible sequence of task movements for the third example is:  move a task from server #4 to server #1 (the sequence m becomes: 2 2 3 3 5);  then move task from server #5 to server #1 (the sequence m becomes: 3 2 3 3 4);  then move task from server #5 to server #2 (the sequence m becomes: 3 3 3 3 3). 

The above sequence is one of several possible ways to balance the load of servers in three seconds.

Source: codeforces | Difficulty: MEDIUM
Tags: Mathematics

Implementation


Solutions:
from collections import Counter
import functools

def main():
	n = int(input())
	arr = [int(i) for i in input().split(' ')]
	arr.sort(reverse=True)
	mean = sum(arr) // n
	err = 0
	new_arr = [mean for i in range(n)]
	for i in range(len(arr)):
		err += arr[i] - mean
	for i in range(n):
		if err == 0:
			break
		new_arr[i] += 1
		err -= 1
	res = 0
	for i in range(n):
		res += abs(arr[i] - new_arr[i])
	print(res // 2)
main()


from __future__ import print_function
import sys
import math
n = int(input())
M = list(map(int, input().split()))
avg = sum(M) / len(M)
ceil = math.ceil(avg)
floor = math.floor(avg)
ceil_count = 0
floor_count = 0
for m in M:
	if m > ceil:
		ceil_count = ceil_count + m - ceil
	if m < floor:
		floor_count = floor_count + floor - m
count = max(ceil_count, floor_count)
print(count)


import math
n = int(input())
l = list(map(int, input().split()))
mean = sum(l) / n
up = 0
down = 0
for x in l:
	if x > mean:
		down += math.floor(x - mean)
	elif x < mean:
		up += math.floor(mean - x)
print(max(up, down))


N = int(input())
a = input().split()
put = []
for i in a:
	put.append(int(i))
average = sum(put) / N
step1 = 0
step2 = 0
for i in put:
	if int(average) == average:
		if i > average:
			step1 += i - average
		else:
			step2 += average - i
	if int(average) != average:
		if i > int(average) + 1:
			step1 += i - int(average + 1)
		if i < int(average):
			step2 += int(average) - i
print(int(max(step1, step2)))


n = int(input())
a = list(map(int, input().split()))
a.sort()
s = sum(a)
whole = s // n
bigger = s % n
smaller = n - bigger
res = 0
for i in range(smaller):
	res += abs(a[i] - whole)
for i in range(smaller, n):
	res += abs(a[i] - whole - 1)
print(res // 2)


n = int(input())
m = list(map(int, input().split()))
(a, b) = (sum(m) // n, (sum(m) + n - 1) // n)
print(max(sum((a - x for x in m if x < a)), sum((x - b for x in m if x > b))))


import sys, os
from io import BytesIO, IOBase
import collections, itertools, bisect, heapq, math, string
from decimal import *
BUFSIZE = 8192
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def main():
	n = int(input())
	a = list(map(int, input().split()))
	sa = sorted(a)
	(l, r) = (math.floor(sum(a) / n), math.ceil(sum(a) / n))
	(t1, t2) = (n - sum(a) % n, sum(a) % n)
	b = [l] * t1 + [r] * t2
	ans = 0
	for i in range(n):
		ans += abs(sa[i] - b[i])
	print(ans // 2)
main()


import math
n = int(input())
lst = [int(i) for i in input().split()]
lst.sort()
total = sum(lst)
more = total - math.floor(total / n) * n
result = [math.floor(total / n) for i in range(n)]
for i in range(n - more, n):
	result[i] += 1
sum_move = 0
for (ori, res) in zip(lst, result):
	if ori > res:
		sum_move = sum_move + (ori - res)
print(sum_move)


n = int(input())
m = list(map(int, input().split()))
s = sum(m)
p = s % n
a = s // n
a_m = []
for _ in range(p):
	a_m.append(a + 1)
for _ in range(n - p):
	a_m.append(a)
m.sort(reverse=True)
res = 0
for i in range(n):
	res += abs(a_m[i] - m[i])
print(res // 2)


n = int(input())
a = sorted(map(int, input().split()))
s = sum(a)
(avg, mid) = (s // n, s % n)
ans = 0
while a:
	d = avg
	if mid:
		d += 1
		mid -= 1
	ans += abs(a.pop() - d)
print(ans // 2)


import sys
input = sys.stdin.readline
n = int(input())
m = list(map(int, input().split()))
m.sort()
s = sum(m)
l = []
for i in range(n):
	if i < s % n:
		l.append(s // n + 1)
	else:
		l.append(s // n)
l = l[::-1]
ans = 0
for (mi, li) in zip(m, l):
	ans += abs(mi - li)
print(ans // 2)


n = int(input())
arr = list(map(int, input().split()))
arr = sorted(arr, reverse=True)
flag = sum(arr) % n
k = int(sum(arr) / n)
ans = 0
count = 0
for i in range(n):
	if count < flag:
		ans += abs(k + 1 - arr[i])
	else:
		ans += abs(k - arr[i])
	count += 1
print(int(ans / 2))


n = int(input())
a = list(map(int, input().split()))
s = sum(a)
a.sort(reverse=True)
out = [s // n] * n
rem = s % n
for i in range(rem):
	out[i] += 1
res = 0
for i in range(n):
	res += abs(a[i] - out[i])
print(res // 2)


from math import ceil
m = int(input())
a = [int(s) for s in input().split()]
sum = 0
for i in range(m):
	sum += a[i]
q = sum // m
a.sort()
ans = 0
for i in range(m - (sum - q * m)):
	ans += abs(a[i] - q)
for i in range(m - (sum - q * m), m):
	ans += abs(a[i] - q - 1)
print(ans // 2)


n = int(input())
a = list(map(int, input().split()))
cur = 0
for i in a:
	cur += i
b = []
for i in range(cur % n):
	b.append((cur + n - 1) // n)
for i in range(n - cur % n):
	b.append(cur // n)
b.sort()
a.sort()
ans = 0
for i in range(n):
	ans += abs(a[i] - b[i])
print(ans // 2)


import math
n = int(input())
a = list(map(int, input().rstrip().split()))
b = sorted(a)[::-1]
s = sum(a)
c = []
resto = s % n
for i in range(n):
	if i < resto:
		c.append(math.ceil(s / n))
	else:
		c.append(math.floor(s / n))
somma = 0
for i in range(n):
	somma += abs(b[i] - c[i])
somma = somma // 2
print(somma)


from functools import reduce
from operator import *
from math import *
from sys import *
from string import *
from collections import *
setrecursionlimit(10 ** 7)
dX = [-1, 1, 0, 0, -1, 1, -1, 1]
dY = [0, 0, -1, 1, 1, -1, -1, 1]
RI = lambda : list(map(int, input().split()))
RS = lambda : input().rstrip().split()
n = RI()[0]
m = RI()
m.sort()
tot = sum(m)
avg = tot // n
ans = 0
i = 0
while i < n and m[i] <= avg:
	ans += avg - m[i]
	i += 1
ans += max(tot % n - (n - i), 0)
print(ans)


n = int(input())
arr = sorted(map(int, input().split()))
summ = sum(arr)
if summ % n == 0:
	div = summ // n
	new = [div] * n
else:
	rem = summ % n
	div = summ // n
	new = [div] * n
	for i in range(rem):
		new[n - 1 - i] += 1
cost = 0
for i in range(n):
	cost += abs(arr[i] - new[i])
print(cost // 2)


def solve():
	N = int(input())
	tasks = list(map(int, input().split()))
	avg = sum(tasks) // N
	missing = [max(avg - t, 0) for t in tasks]
	remaining = [max(t - avg - 1, 0) for t in tasks]
	print(max(sum(missing), sum(remaining)))

def __starting_point():
	solve()
__starting_point()


n = int(input())
a = [int(x) for x in input().split()]
s = sum(a)
m1 = s // n
k = s % n
cnt_less = 0
less = 0
cnt_m1 = 0
cnt_m2 = 0
for i in range(n):
	if a[i] < m1:
		cnt_less += 1
		less += m1 - a[i]
	elif a[i] == m1:
		cnt_m1 += 1
	elif a[i] == m1 + 1:
		cnt_m2 += 1
if cnt_m1 == n - k and cnt_m2 == k:
	print(0)
else:
	if cnt_less + cnt_m1 > n - k:
		less += cnt_less + cnt_m1 - (n - k)
	print(less)


import unittest
import sys

class Load:

	def __init__(self, test_inputs=None):
		it = iter(test_inputs.split('\n')) if test_inputs else None

		def uinput():
			return next(it) if it else sys.stdin.readline().rstrip()
		[self.n] = map(int, uinput().split())
		self.nums = list(map(int, uinput().split()))
		self.snums = list(reversed(sorted(self.nums)))
		self.summ = sum(self.nums)
		self.avg = self.summ // self.n
		self.numavgp1 = self.summ - self.avg * self.n
		self.targ = [self.avg + 1] * self.numavgp1
		self.targ += [self.avg] * (self.n - self.numavgp1)

	def calculate(self):
		result = 0
		for i in range(self.n):
			delta = self.snums[i] - self.targ[i]
			result += delta if delta > 0 else 0
		return str(result)

class unitTests(unittest.TestCase):

	def test_single_test(self):
		test = '2\n1 6'
		d = Load(test)
		self.assertEqual(d.n, 2)
		self.assertEqual(d.nums, [1, 6])
		self.assertEqual(d.snums, [6, 1])
		self.assertEqual(d.targ, [4, 3])
		self.assertEqual(Load(test).calculate(), '2')
		test = '7\n10 11 10 11 10 11 11'
		self.assertEqual(Load(test).calculate(), '0')
		test = '5\n1 2 3 4 5'
		self.assertEqual(Load(test).calculate(), '3')
		test = ''

	def time_limit_test(self, nmax):
		import random
		import timeit
		test = str(nmax) + ' ' + str(nmax) + '\n'
		numnums = [str(i) + ' ' + str(i + 1) for i in range(nmax)]
		test += '\n'.join(numnums) + '\n'
		nums = [random.randint(1, 10000) for i in range(nmax)]
		test += ' '.join(map(str, nums)) + '\n'
		start = timeit.default_timer()
		d = Load(test)
		calc = timeit.default_timer()
		d.calculate()
		stop = timeit.default_timer()
		print('\nTimelimit Test: ' + '{0:.3f}s (init {1:.3f}s calc {2:.3f}s)'.format(stop - start, calc - start, stop - calc))
sys.setrecursionlimit(100000)
if sys.argv[-1] == '-ut':
	unittest.main(argv=[' '])
sys.stdout.write(Load().calculate())


N = int(input())
M = list(map(int, input().split()))
M.sort()
avg_lo = sum(M) // N
avg_hi = (sum(M) + N - 1) // N
ans1 = 0
ans2 = 0
for m in M:
	ans1 += max(avg_lo - m, 0)
	ans2 += max(m - avg_hi, 0)
print(max(ans1, ans2))


def main():

	def solve2():
		a = m[:]
		cnt = 0
		t = 1 if Sum % n else 0
		while max(a) - min(a) != t:
			mn = a.index(min(a))
			mx = a.index(max(a))
			a[mn] += 1
			a[mx] -= 1
			cnt += 1
		return cnt
	n = int(input())
	m = list(map(int, input().split()))
	Sum = sum(m)
	mid = Sum // n
	if Sum % n == 0:
		ans = sum((abs(i - mid) for i in m)) // 2
	else:
		cntscd = Sum % n
		cnt = ans = 0
		for i in m:
			if i > mid and cnt < cntscd:
				cnt += 1
				ans += i - mid - 1
			else:
				ans += abs(mid - i)
		ans += cntscd - cnt
		ans = ans // 2
	print(ans)
main()


import sys
n = int(input())
a = sorted(map(int, input().split()))
total = sum(a)
x = total // n
y = (total + n - 1) // n
collect = [x] * (n - total % n) + [y] * (total % n)
ans = 0
for i in range(n):
	delta = collect[i] - a[i]
	if delta > 0:
		ans += delta
print(ans)


n = int(input())
servers = list(map(int, input().split()))
Sum = sum(servers)
average = Sum // n
flag = Sum % n == 0
ans = 0
cnt = 0
for i in range(n):
	if servers[i] <= average:
		ans += average - servers[i]
		cnt += 1
left = n - cnt
if not flag:
	ans += max(Sum % n - left, 0)
print(ans)


n = int(input())
l = list(map(int, input().split()))
s = sum(l)
xs = s // n
ys = s % n
nxs = n - ys
ls = [0] * n
l.sort()
for i in range(n):
	if i < nxs:
		ls[i] = abs(l[i] - xs)
	else:
		ls[i] = abs(xs + 1 - l[i])
print(sum(ls) // 2)


import math
n = int(input())
l = list(map(int, input().split()))
if n == 1:
	print(0)
	exit()
l.sort()
som = sum(l)
if som % n == 0:
	ans = 0
	i = 0
	j = n - 1
	target = som // n
	rem = 0
	while i < j:
		x = l[j]
		diff = x - target
		l[j] -= diff
		diff2 = target - l[i]
		ans += diff
		ans += diff2
		i = i + 1
		j = j - 1
	print(ans // 2)
else:
	ans = 0
	target = math.ceil(som / n)
	cnt1 = som % n
	cnt2 = n - cnt1
	c = 0
	i = 0
	while i < n:
		x = l[i]
		if c < cnt2:
			diff = abs(x - (target - 1))
			ans += diff
			c += 1
		else:
			diff = abs(x - target)
			ans += diff
		i += 1
	print(ans // 2)


N = int(input())
M = list(map(int, input().strip().split()))
M.sort(reverse=True)
s = sum(M)
k = s // N
j = s % N
d = 0
for i in range(N):
	if i < j:
		d += abs(M[i] - k - 1)
	else:
		d += abs(M[i] - k)
print(d // 2)


import math

def main():
	n = int(input())
	m = list(map(int, input().split()))
	m.sort()
	s = sum(m)
	n1 = s % n
	n2 = n - n1
	k = s / n
	up = math.ceil(k)
	down = math.floor(k)
	ans1 = 0
	ans2 = 0
	for i in m:
		if i < down:
			ans1 += abs(down - i)
		elif i > up:
			ans2 += abs(up - i)
	print(max(ans1, ans2))
main()


n = int(input())
servers = list(map(int, input().split()))
s = sum(servers)
m = s // n
mod = s % n
total = 0
servers.sort()
for i in range(n - 1, n - mod - 1, -1):
	total += abs(servers[i] - m - 1)
for i in range(n - mod - 1, -1, -1):
	total += abs(servers[i] - m)
print(total // 2)


from math import floor, ceil
n = int(input())
s = list(map(int, input().split()))
s.sort()
t = sum(s)
mid = t // n
rem = t % n
ans = 0
v = [mid] * len(s)
for i in range(rem):
	v[n - (i + 1)] += 1
for i in range(n):
	ans += abs(s[i] - v[i])
print(ans // 2)


n = int(input())
m = list(map(int, input().split(' ')))
summ = sum(m)
avg = summ // n
remainder = summ % n
more_avg = [x for x in m if x > avg]
more_avg = sorted(more_avg, reverse=True)
number_more_avg = len(more_avg)
if remainder >= number_more_avg:
	time_for_each = [x - avg - 1 for x in more_avg]
	time = sum(time_for_each)
elif (remainder < number_more_avg) & (remainder > 0):
	time_for_each_with_remainder = [x - avg - 1 for x in more_avg[:remainder]]
	time_for_each_without_remainder = [x - avg for x in more_avg[remainder:]]
	time = sum(time_for_each_with_remainder) + sum(time_for_each_without_remainder)
else:
	time_for_each = [x - avg for x in more_avg]
	time = sum(time_for_each)
print(time)


n = int(input())
m = list(map(int, input().split()))
m.sort(reverse=True)
diff = sum(m) % n
each = sum(m) // n
res = 0
for i in range(n):
	if diff != 0 and m[i] > each + 1:
		res += m[i] - (each + 1)
		diff -= 1
	elif diff == 0 and m[i] > each:
		res += m[i] - each
print(res)


from math import *
n = int(input())
a = list(map(int, input().split(' ')))
b = []
x = 0
y = 0
sm = 0
k = 0
o = 0
for i in range(n):
	sm += a[i]
k = sm // n
for i in range(n):
	b.append(k)
	if i < sm % n:
		b[i] += 1
a.sort()
b.sort()
for i in range(n):
	o += abs(a[i] - b[i])
print(o // 2)


import math
n = int(input())
arr = [int(x) for x in input().split()]
ideal = []
s = 0
for i in arr:
	s += i
div = int(s / n)
rem = s % n
for i in range(0, n):
	if rem > 0:
		ideal.insert(i, div + 1)
		rem -= 1
	else:
		ideal.insert(i, div)
ideal.sort()
arr.sort()
ans = 0
for i in range(0, n):
	ans += int(abs(ideal[i] - arr[i]))
print(int(ans / 2))


n = int(input())
L = [int(x) for x in input().split(' ')]
L.sort()
tot = sum(L)
small = tot // n
numsmall = n - (tot - small * n)
ans = 0
for i in range(0, numsmall):
	ans += max(0, small - L[i])
for i in range(numsmall, n):
	ans += max(0, small + 1 - L[i])
print(ans)


import bisect
n = int(input())
c = 0
mas = [int(x) for x in input().split()]
s = sum(mas)
u = k = s // n
f = s % n
k += f > 0
mas.sort()
o = bisect.bisect_right(mas, u)
if o == n:
	print(c)
	quit()
for i in range(o, n):
	if n - i > f:
		c += mas[i] - u
	else:
		c += mas[i] - k
print(c)


n = int(input())
s = sorted([int(i) for i in input().split()], reverse=True)
sm = sum(s)
up = sm - sm // n * n
for i in range(up):
	s[i] -= 1
res = 0
for i in [j for j in s if j > sm // n]:
	res += i - sm // n
print(res)


n = int(input())
m = list(map(int, input().split()))
m.sort()
t = sum(m)
cnt = 0
mid = t // n
rem = t % n
v = [mid] * n
for i in range(rem):
	v[n - (i + 1)] += 1
for i in range(n):
	cnt += abs(m[i] - v[i])
print(cnt // 2)


n = int(input())
a = list(map(int, input().split()))
s = sum(a)
l = s // n
if s % n == 0:
	r = l
else:
	r = l + 1
k1 = k2 = 0
for x in a:
	if x < l:
		k1 += l - x
	elif x > r:
		k2 += x - r
print(max(k1, k2))


import sys
import math
import collections
import heapq
import decimal
input = sys.stdin.readline
n = int(input())
l = sorted([int(i) for i in input().split()])
s = sum(l)
k1 = s // n
k2 = math.ceil(s / n)
c = s - k1 * n
l1 = [k1] * (n - c) + [k2] * c
c1 = 0
for i in range(n):
	c1 += abs(l[i] - l1[i])
print(c1 // 2)


n = int(input())
mas = list(map(int, input().split()))
mas.sort()
d = sum(mas) // n
a = n - sum(mas) % n
b = n - a
ans = 0
for i in range(a):
	ans += abs(mas[i] - d)
for i in range(a, a + b):
	ans += abs(mas[i] - d - 1)
print(ans // 2)


def main():
	n = int(input())
	L = [int(x) for x in input().split()]
	print(solver(n, L))

def solver(n, L):
	total = sum(L)
	smaller = total // n
	lCount = total - n * smaller
	sCount = n - lCount
	if lCount == 0:
		larger = smaller
	else:
		larger = smaller + 1
	changes = 0
	for x in L:
		if x < smaller:
			if sCount > 0:
				changes += smaller - x
				sCount -= 1
			else:
				changes += larger - x
				lCount -= 1
		elif x > larger:
			if lCount > 0:
				changes += x - larger
				lCount -= 1
			else:
				changes += x - smaller
				sCount -= 1
		elif x == smaller:
			if sCount == 0:
				changes += 1
				lCount -= 1
			else:
				sCount -= 1
		elif x == larger:
			if lCount == 0:
				changes += 1
				sCount -= 1
			else:
				lCount -= 1
		else:
			assert False
	return changes // 2
main()


number = int(input())
servers = list(map(int, input().split()))
ans = 0
mload = sum(servers) // number
if not sum(servers) % number:
	for i in range(number):
		if servers[i] < mload:
			ans += mload - servers[i]
else:
	gload = 0
	cnt = 0
	for i in range(number):
		if servers[i] < mload:
			ans += mload - servers[i]
		elif servers[i] > mload:
			cnt += 1
		gload += mload - servers[i]
	if cnt < abs(gload):
		ans += abs(gload) - cnt
print(ans)


n = int(input())
a = [int(i) for i in input().split()]
a.sort()
Yu = sum(a) % n
pin = sum(a) // n
re = 0
for i in a:
	if i < pin:
		re += pin - i
	else:
		break
if Yu == 0:
	print(re)
else:
	re_2 = 0
	for i in a:
		if i <= pin + 1:
			continue
		else:
			re_2 += i - pin - 1
	print(max(re, re_2))


n = int(input())
a = list(map(int, input().split()))
s = sum(a)
a.sort()
need = s // n
rem = s % n
f = [need] * n
for i in range(n - 1, -1, -1):
	if rem == 0:
		break
	f[i] += 1
	rem -= 1
ans = 0
for i in range(n):
	if a[i] > f[i]:
		ans += a[i] - f[i]
print(ans)


import time
n = int(input())
m = [int(i) for i in input().split()]
start = time.time()
s = divmod(sum(m), n)[0]
a1 = 0
a2 = 0
for i in m:
	if i < s:
		a1 += s - i
	if i > s + 1:
		a2 += i - s - 1
print(max(a1, a2))
finish = time.time()


n = int(input())
m = [int(i) for i in input().split(' ')]
s = sum(m)
(t, sm, p) = (0, s // n, n - s % n)
k = 0
for i in m:
	if k == p:
		sm += 1
		k += 1
	if i <= sm:
		t += sm - i
		k += 1
print(t)


def inpList():
	return list(map(int, input().split()))

def inp():
	return int(input())
n = inp()
a = inpList()
x = sum(a)
p = x // n
t = x % n
a.sort()
suma = 0
for i in range(n - t):
	suma += abs(p - a[i])
for i in range(n - t, n):
	suma += abs(a[i] - p - 1)
print(suma // 2)


import sys
n = int(input())
a = list(map(int, input().split()))
x = 0
a.sort()
ans = 0
sm = sum(a)
for i in range(len(a)):
	x = sm // n
	ans += abs(x - a[i])
	n -= 1
	sm -= x
print(ans // 2)


n = int(input())
l = list(map(int, input().split()))
Sum = sum(l)
lower_avg = Sum // n
upper_avg = lower_avg + 1 if Sum % n != 0 else lower_avg
print(max(sum((i - upper_avg for i in l if i > upper_avg)), sum((lower_avg - i for i in l if i < lower_avg))))


def grimper(M):
	k = 1
	while M[k] < M[k - 1]:
		(M[k], M[k - 1]) = (M[k - 1], M[k])
		k += 1
	k = n - 1
	while M[k] < M[k - 1]:
		(M[k], M[k - 1]) = (M[k - 1], M[k])
		k -= 1
	return M
n = int(input())
M = list(map(int, input().split()))
s = sum(M)
m = s // n
if s % n:
	c = 1
else:
	c = 0
r1 = 0
r2 = 0
for k in range(n):
	if M[k] < m:
		r1 += m - M[k]
	if M[k] > m + c:
		r2 += M[k] - (m + c)
print(max([r1, r2]))


def solve(arr, n):
	arr.sort()
	ans = 0
	avg = sum(arr) // n
	rem = sum(arr) % n
	for i in range(n):
		if i < n - rem:
			diff = arr[i] - avg
		else:
			diff = arr[i] - (avg + 1)
		if diff > 0:
			ans += diff
	return ans
n = int(input())
arr = [int(ele) for ele in input().strip().split()]
print(solve(arr, n))


n = int(input())
m = list(map(int, input().split()))
avg = sum(m) / n
sum_positive = sum_negative = 0
for i in range(n):
	dif = int(avg - m[i])
	if dif > 0:
		sum_positive += dif
	else:
		sum_negative += dif
print(max(sum_positive, -sum_negative))


n = int(input())
ns = input().split()
for i in range(len(ns)):
	ns[i] = int(ns[i])
s = 0
avg = sum(ns) / n
if avg == int(avg):
	cv = 0
else:
	cv = 1
	avg = int(avg)
pc = 0
nc = 0
ipc = 0
inc = 0
for i in range(n):
	diff = ns[i] - avg
	if abs(diff) > cv:
		if diff > 0:
			pc = pc + diff - cv
		else:
			nc = nc + abs(diff) - cv
	if cv == 1:
		if diff >= 1:
			ipc = ipc + 1
		elif diff <= -1:
			inc = inc + 1
bse = min([pc, nc])
s = int(bse + abs(pc - nc))
pc = pc - bse
nc = nc - bse
ipc = ipc - nc
inc = inc - pc
if ipc > 0 and inc > 0:
	s = int(s + min([ipc, inc]))
print(s)


n = int(input())
m = sorted(map(int, input().split(' ')), reverse=True)
s = sum(m)
(t, r) = (s // n, s % n)
for i in range(r):
	m[i] -= 1
print(sum(map(lambda a: a - t if a > t else 0, m)))


diff = 0
x = int(input())
l = list(map(int, input().split(' ')))
s = sum(l)
k = s // x
knum = (k + 1) * x - s
kpnum = x - knum
a = knum * [k] + [k + 1] * kpnum
a.sort()
l.sort()
for i in range(len(a)):
	diff += abs(a[i] - l[i])
print(int(diff / 2))


n = int(input())
a = list(map(int, input().split()))
s = 0
a.sort(reverse=True)
for i in range(n):
	s += a[i]
cel = int(s / n)
ost = s % n
i = 0
kol = 0
while a[i] > cel:
	if ost != 0:
		kol += a[i] - cel - 1
		ost -= 1
	else:
		kol += a[i] - cel
	i += 1
print(kol)


n = int(input())
lst = [*map(int, input().split())]
summa = sum(lst)
(div, mod) = (summa // n, summa % n)
lst = [*reversed(sorted(lst))]
(res, i) = (0, 0)
for (i, x) in enumerate(lst):
	if x <= div:
		break
	if i < mod:
		res += x - (div + 1)
	else:
		res += x - div
	i += 1
print(res)


import math
a = int(input())
b = list(map(int, input().split()))
c = sum(b) / a
(ans1, ans2) = (0, 0)
for i in b:
	if i > c:
		ans1 += i - math.ceil(c)
	if i < c:
		ans2 += math.floor(c) - i
print(max(ans1, ans2))


n = int(input())
from math import ceil
l = [int(i) for i in input().split()]
s = sum(l)
if sum(l) % n == 0:
	b = [s // n] * n
else:
	rem = s % n
	b = [s // n] * (n - rem) + [ceil(s / n)] * rem
l.sort()
ans = 0
for i in range(n):
	ans = ans + abs(l[i] - b[i])
print(ans // 2)


from math import ceil, floor
n = int(input())
a = list(map(int, input().split()))
s = sum(a)
avg = s / n
res = 0
if avg % 1 == 0:
	avg = int(avg)
	for val in a:
		res += abs(avg - val)
else:
	m = s % n
	new = [ceil(s / n) for _ in range(m)] + [floor(s / n) for _ in range(n - m)]
	a.sort()
	new.sort()
	for i in range(n):
		res += abs(a[i] - new[i])
res = res // 2
print(res)


n = int(input())
A = list(map(int, input().split()))
c = sum(A) // n
r = sum(A) % n
lol = n - r
ans = 0
for d in A:
	if lol == 0:
		ans += abs(d - (c + 1))
	elif r == 0:
		ans += abs(d - c)
	elif d == c:
		lol -= 1
	elif d > c:
		ans += abs(d - (c + 1))
		r -= 1
	else:
		ans += abs(d - c)
		lol -= 1
print(ans // 2)


n = int(input())
serv = list(map(int, input().split()))
serv.sort()
ss = sum(serv)
l = n - ss % n
r = ss % n
it = 0
mid = ss // n
ans = 0
while l > 0:
	ans += abs(serv[it] - mid)
	l -= 1
	it += 1
while r > 0:
	ans += abs(serv[it] - mid - 1)
	r -= 1
	it += 1
ans = ans // 2
print(ans)


input()
servers = [int(x) for x in input().split(' ')]
servers.sort()
avg = int(sum(servers) / len(servers))
extra = sum(servers) % len(servers)
count = 0
for i in range(len(servers)):
	count += abs(avg + (i >= len(servers) - extra) - servers[i]) / 2
print(int(count))


from functools import cmp_to_key
from collections import deque, Counter
from heapq import heappush, heappop
from math import log, ceil
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def ii():
	return int(inp())

def si():
	return str(inp())

def li(lag=0):
	l = list(map(int, inp().split()))
	if lag != 0:
		for i in range(len(l)):
			l[i] += lag
	return l

def mi(lag=0):
	matrix = list()
	for i in range(n):
		matrix.append(li(lag))
	return matrix

def lsi():
	return list(map(str, inp().split()))

def print_list(lista, space=' '):
	print(space.join(map(str, lista)))

def bisect_left(a, x):
	left = 0
	right = len(a)
	while left < right:
		mid = (left + right) // 2
		if a[mid] < x:
			left = mid + 1
		else:
			right = mid
	return left

def bisect_right(a, x):
	left = 0
	right = len(a)
	while left < right:
		mid = (left + right) // 2
		if a[mid] > x:
			right = mid
		else:
			left = mid + 1
	return left

def bisect_elements(a, x):
	return bisect_right(a, x) - bisect_left(a, x)
MOD = 10 ** 9 + 7
maxN = 5
FACT = [0] * maxN
INV_FACT = [0] * maxN

def add(x, y):
	return (x + y) % MOD

def multiply(x, y):
	return x * y % MOD

def power(x, y):
	if y == 0:
		return 1
	elif y % 2:
		return multiply(x, power(x, y - 1))
	else:
		a = power(x, y // 2)
		return multiply(a, a)

def inverse(x):
	return power(x, MOD - 2)

def divide(x, y):
	return multiply(x, inverse(y))

def allFactorials():
	FACT[0] = 1
	for i in range(1, maxN):
		FACT[i] = multiply(i, FACT[i - 1])

def inverseFactorials():
	n = len(INV_FACT)
	INV_FACT[n - 1] = inverse(FACT[n - 1])
	for i in range(n - 2, -1, -1):
		INV_FACT[i] = multiply(INV_FACT[i + 1], i + 1)

def coeffBinom(n, k):
	if n < k:
		return 0
	return multiply(FACT[n], multiply(INV_FACT[k], INV_FACT[n - k]))

def create_graph(n, m, undirected=1, unweighted=1):
	graph = [[] for i in range(n)]
	if unweighted:
		for i in range(m):
			[x, y] = li(lag=-1)
			graph[x].append(y)
			if undirected:
				graph[y].append(x)
	else:
		for i in range(m):
			[x, y, w] = li(lag=-1)
			w += 1
			graph[x].append([y, w])
			if undirected:
				graph[y].append([x, w])
	return graph

def create_tree(n, unweighted=1):
	children = [[] for i in range(n)]
	if unweighted:
		for i in range(n - 1):
			[x, y] = li(lag=-1)
			children[x].append(y)
			children[y].append(x)
	else:
		for i in range(n - 1):
			[x, y, w] = li(lag=-1)
			w += 1
			children[x].append([y, w])
			children[y].append([x, w])
	return children

def dist(tree, n, A, B=-1):
	s = [[A, 0]]
	(massimo, massimo_nodo) = (0, 0)
	distanza = -1
	v = [-1] * n
	while s:
		(el, dis) = s.pop()
		if dis > massimo:
			massimo = dis
			massimo_nodo = el
		if el == B:
			distanza = dis
		for child in tree[el]:
			if v[child] == -1:
				v[child] = 1
				s.append([child, dis + 1])
	return (massimo, massimo_nodo, distanza)

def diameter(tree):
	(_, foglia, _) = dist(tree, n, 0)
	(diam, _, _) = dist(tree, n, foglia)
	return diam

def dfs(graph, n, A):
	v = [-1] * n
	s = [[A, 0]]
	v[A] = 0
	while s:
		(el, dis) = s.pop()
		for child in graph[el]:
			if v[child] == -1:
				v[child] = dis + 1
				s.append([child, dis + 1])
	return v

def bfs(graph, n, A):
	v = [-1] * n
	s = deque()
	s.append([A, 0])
	v[A] = 0
	while s:
		(el, dis) = s.popleft()
		for child in graph[el]:
			if v[child] == -1:
				v[child] = dis + 1
				s.append([child, dis + 1])
	return v

def parents_children_root_unrooted_tree(tree, n, root=0):
	q = deque()
	visited = [0] * n
	parent = [-1] * n
	children = [[] for i in range(n)]
	q.append(root)
	while q:
		all_done = 1
		visited[q[0]] = 1
		for child in tree[q[0]]:
			if not visited[child]:
				all_done = 0
				q.appendleft(child)
		if all_done:
			for child in tree[q[0]]:
				if parent[child] == -1:
					parent[q[0]] = child
					children[child].append(q[0])
			q.popleft()
	return (parent, children)

def all_longest_path_passing_from_node(parent, children, n):
	q = deque()
	visited = [len(children[i]) for i in range(n)]
	downwards = [[0, 0] for i in range(n)]
	upward = [1] * n
	longest_path = [1] * n
	for i in range(n):
		if not visited[i]:
			q.append(i)
			downwards[i] = [1, 0]
	while q:
		node = q.popleft()
		if parent[node] != -1:
			visited[parent[node]] -= 1
			if not visited[parent[node]]:
				q.append(parent[node])
		else:
			root = node
		for child in children[node]:
			downwards[node] = sorted([downwards[node][0], downwards[node][1], downwards[child][0] + 1], reverse=True)[0:2]
	s = [node]
	while s:
		node = s.pop()
		if parent[node] != -1:
			if downwards[parent[node]][0] == downwards[node][0] + 1:
				upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][1])
			else:
				upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][0])
		longest_path[node] = downwards[node][0] + downwards[node][1] + upward[node] - min([downwards[node][0], downwards[node][1], upward[node]]) - 1
		for child in children[node]:
			s.append(child)
	return longest_path

def dist(x, t):
	return abs(x - t)
n = ii()
a = sorted(li())
s = sum(a)
if s % n == 0:
	m = s // n
	M = s // n
	nm = n
else:
	m = s // n
	M = s // n + 1
	nm = M * n - s
somme = 0
for i in range(n):
	if i < nm:
		somme += dist(a[i], m)
	else:
		somme += dist(a[i], M)
print(somme // 2)


from math import *
n = int(input())
s1 = 0
s2 = 0
a = list(map(int, input().split()))
sr = sum(a) / n
for i in a:
	if i > sr:
		s1 += i - ceil(sr)
	if sr > i:
		s2 += floor(sr) - i
print(max(s1, s2))


n = int(input())
tasks = input().split()
tasks = [int(t) for t in tasks]
sumTasks = sum(tasks)
average1 = sumTasks // n
if sumTasks % n == 0:
	average2 = average1
else:
	average2 = average1 + 1
count1 = 0
count2 = 0
for i in range(len(tasks)):
	if tasks[i] < average1:
		count1 += average1 - tasks[i]
	elif tasks[i] > average2:
		count2 += tasks[i] - average2
print(max(count1, count2))


n = int(input())
m = list(map(int, input().split()))
m.sort()
summ = sum(m)
ans = 0
x = summ // n
y = n * (x + 1) - summ
for i in range(n):
	if i == y:
		x += 1
	if m[i] <= x:
		ans += x - m[i]
print(ans)


(n, ans) = (int(input()), 0)
a = sorted(map(int, input().split()))
s = sum(a)
for i in range(n):
	ans += abs(a[i] - s // n - (i >= n - s % n))
print(ans // 2)


n = int(input())
a = list(map(int, input().split()))
a.sort()
sum = 0
for i in range(n):
	sum += a[i]
z1 = sum // n
z2 = sum // n + 1
col = sum % n
col = n - col
ans = 0
for i in range(col):
	ans += abs(z1 - a[i])
for t in range(col, n):
	ans += abs(a[t] - z2)
print(ans // 2)


import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
a.sort()
b = sum(a) // n
c = [b] * n
for i in range(sum(a) % n):
	c[i] += 1
c = c[::-1]
s = 0
for i in range(n):
	s += abs(c[i] - a[i])
print(s // 2)


n = int(input())
k = list(map(int, input().split()))
s = sum(k)
smin = s // n
smax = round(s / n + 0.49)
tmin = 0
tmax = 0
k.sort()
for i in range(n):
	if k[i] >= smin:
		break
	tmin += smin - k[i]
for i in range(n, 1, -1):
	if k[i - 1] <= smax:
		break
	tmax += k[i - 1] - smax
print(max(tmin, tmax))


import math
import logging
import copy
import sys
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)

def solve(line):
	s = sum(line)
	avg = math.ceil(s / len(line))
	over = list(filter(lambda x: x > avg, line))
	over = list(map(lambda x: x - avg, over))
	avg = s // len(line)
	under = list(filter(lambda x: x < avg, line))
	under = list(map(lambda x: avg - x, under))
	sumOver = sum(over)
	sumUnder = sum(under)
	log(sumOver, sumUnder)
	m = abs(sumOver - sumUnder)
	return max(sumUnder, sumOver)

def main():
	firstLine = input().split()
	firstLine = list(map(int, firstLine))
	line = input().split()
	line = list(map(int, line))
	print(solve(line))

def log(*message):
	logging.debug(message)
main()


from math import floor, ceil
n = int(input())
v = [int(x) for x in input().split()]
avg = sum(v) / len(v)
avg_min = floor(avg)
avg_max = ceil(avg)
(sol_min, sol_max) = (0, 0)
for x in v:
	if x <= avg_min:
		sol_min += abs(x - avg_min)
	else:
		sol_max += abs(x - avg_max)
print(max(sol_min, sol_max))


def main():
	n = int(input())
	sp = list(map(int, input().split()))
	sp_sum = sum(sp)
	t1 = sp_sum // n
	k_t2 = sp_sum % n
	ans = 0
	sp.sort(reverse=True)
	i = 0
	for i in range(n):
		if sp[i] > t1:
			if k_t2 > 0:
				ans += sp[i] - (t1 + 1)
				k_t2 -= 1
			else:
				ans += sp[i] - t1
	print(ans)
main()


ans = 0
n = int(input())
s = list(map(int, input().split()))
k1 = sum(s) // n
k2 = (sum(s) + n - 1) // n
a1 = a2 = 0
for i in s:
	if i < k1:
		a1 += abs(i - k1)
	elif i > k2:
		a2 += abs(i - k2)
print(max(a1, a2))


from sys import stdin

def main():
	n = int(stdin.readline())
	ar = list(map(int, stdin.readline().split()))
	ar.sort()
	total = sum(ar)
	base = total // n
	count = total % n
	ans = 0
	for i in range(n - 1, -1, -1):
		if count > 0 and ar[i] >= base + 1:
			ans += ar[i] - base - 1
			count -= 1
		elif ar[i] > base:
			ans += ar[i] - base
	print(ans)
main()


n = int(input())
m = list(map(int, input().split()))
total = sum(m)
lower_avg = total // n
upper_avg = lower_avg + 1 if total > lower_avg * n else lower_avg
result = max(sum((i - upper_avg for i in m if i > upper_avg)), sum((lower_avg - i for i in m if i < lower_avg)))
print(result)


n = int(input())
l = input().split()
s = 0
for i in range(n):
	l[i] = int(l[i])
	s += l[i]
if s % n == 0:
	q = s // n
	r = 0
	for i in range(n):
		if l[i] > q:
			r += l[i] - q
	print(r)
else:
	p = s % n
	q = (s - s % n) // n
	r = 0
	l.sort()
	l.reverse()
	for i in range(n):
		if i < p:
			if l[i] > q + 1:
				r += l[i] - q - 1
		elif l[i] > q:
			r += l[i] - q
	print(r)


n = int(input())
m = list(map(int, input().split()))
s = sum(m)
if s % n == 0:
	res = 0
	for x in m:
		res += abs(x - s // n)
	print(res // 2)
else:
	(lo, hi) = (s // n, s // n + 1)
	(res1, res2) = (0, 0)
	for x in m:
		if x < lo:
			res1 += lo - x
		elif x > hi:
			res2 += x - hi
	print(max(res1, res2))


import sys
from bisect import bisect_right as rb
from collections import deque
from queue import PriorityQueue
from math import *
input_ = lambda : sys.stdin.readline().strip('\r\n')
ii = lambda : int(input_())
il = lambda : list(map(int, input_().split()))
ilf = lambda : list(map(float, input_().split()))
ip = lambda : input_()
fi = lambda : float(input_())
ap = lambda ab, bc, cd: ab[bc].append(cd)
li = lambda : list(input_())
pr = lambda x: print(x)
prinT = lambda x: print(x)
f = lambda : sys.stdout.flush()
mod = 10 ** 9 + 7
n = ii()
a = il()
a.sort()
t = sum(a)
x = t // n
y = t % n
z = n - y
s = 0
for i in range(n):
	if i < z:
		s += abs(a[i] - x)
	else:
		s += abs(a[i] - 1 - x)
print(s // 2)


n = int(input())
A = list(map(int, input().split()))
SUM = sum(A)
(a, b) = (0, 0)
if SUM % n == 0:
	(a, b) = (SUM // n, SUM // n)
else:
	(a, b) = (SUM // n, SUM // n + 1)
(counta, countb) = (0, 0)
for val in A:
	if val < a:
		counta += abs(a - val)
	if val > b:
		countb += abs(val - b)
if counta >= countb:
	print(counta)
else:
	print(countb)


n = int(input())
m = [int(x) for x in input().split()]
m.sort()
sum_m = sum(m)
mean = sum_m // n
dif = sum_m - mean * n
res = 0
for i in range(n):
	if i < n - dif:
		res += abs(m[i] - mean)
	else:
		res += abs(m[i] - mean - 1)
print(res // 2)


try:
	while True:
		n = int(input())
		a = list(map(int, input().split()))
		a.sort()
		s = sum(a)
		(average, top) = divmod(s, n)
		result = 0
		if top != 0:
			for x in a[-top:]:
				result += abs(x - average - 1)
			for x in a[:-top]:
				result += abs(average - x)
		else:
			for x in a:
				result += abs(average - x)
		print(result >> 1)
except EOFError:
	pass


n = int(input())
a = list(map(int, input().split()))
a.sort()
k = sum(a)
t = k % n
avg = k // n
fin = 0
for i in range(n - t):
	fin += abs(a[i] - avg)
for i in range(n - t, n):
	fin += abs(a[i] - avg - 1)
print(fin // 2)


n = int(input())
m = sorted([int(x) for x in input().split()])
avg = sum(m) // len(m)
rem = sum(m) - avg * n
lst = [avg] * (n - rem) + [avg + 1] * rem
print(sum([abs(lst[i] - m[i]) for i in range(n)]) // 2)


__author__ = 'Utena'
import math
n = int(input())
s = list(map(int, input().split()))
sum = sum(s)
a = sum / n
l = math.floor(a)
t = 0
t1 = 0
for x in s:
	if x < l:
		t += l - x
	elif x > l + 1:
		t1 += x - l - 1
t = max(t, t1)
print(t)


import os, sys
from io import IOBase, BytesIO
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import sys

class ostream:

	def __lshift__(self, a):
		sys.stdout.write(str(a))
		return self
cout = ostream()
endl = '\n'

def solve():
	n = int(input())
	arr = list(map(int, input().split()))
	sm = sum(arr)
	v2 = sm // n
	v1 = v2 + 1
	v1_freq = sm % n
	v2_freq = n - v1_freq
	arr.sort(reverse=True)
	res = 0
	curr_res = 0
	for i in range(len(arr)):
		if v1_freq and arr[i] > v1:
			curr_res += arr[i] - v1
			v1_freq -= 1
		elif v1_freq == 0 and v2_freq and (arr[i] > v2):
			curr_res += arr[i] - v2
			v2_freq -= 1
		res = max(res, curr_res)
	cout << res << endl

def main():
	solve()
main()


n = int(input())
m = [int(x) for x in input().split()]
avg = sum(m) // len(m)
if avg * n == sum(m):
	print(sum([max(0, avg - x) for x in m]))
else:
	x = sum([max(0, x - avg - 1) for x in m])
	y = sum([max(0, avg - x) for x in m])
	print(max(x, y))


import math
n = int(input())
m = input().split()
end = []
for i in range(len(m)):
	m[i] = int(m[i])
min_req = math.floor(sum(m) / len(m))
remainder = sum(m) % len(m)
m.sort()
for i in range(len(m)):
	end.append(min_req)
for i in range(remainder):
	end[i] += 1
end.sort()
counter = 0
for i in range(len(m)):
	counter += abs(m[i] - end[i])
counter /= 2
print(int(counter))


n = int(input())
L = [int(x) for x in input().split(' ')]
L.sort()
tot = sum(L)
small = tot // n
num_small = n - (tot - small * n)
steps = 0
for i in range(num_small):
	steps += max(0, small - L[i])
for i in range(num_small, n):
	steps += max(0, small + 1 - L[i])
print(steps)


n = int(input())
a = list(map(int, input().split()))
s = sum(a)
min_s = s // n
p = 0
res = []
if s % n == 0:
	max_s = s // n
	for i in range(n):
		if a[i] != min_s:
			p += abs(a[i] - min_s)
	print(p // 2)
else:
	max_s = min_s + 1
	for j in range(n + 1):
		if j * min_s + (n - j) * max_s == s:
			p = 0
			min_k = j
			max_k = n - min_k
			for i in range(n):
				if a[i] <= min_s:
					if min_k > 0:
						p += abs(a[i] - min_s)
						min_k -= 1
					else:
						p += abs(a[i] - max_s)
						max_k -= 1
				elif max_k > 0:
					p += abs(a[i] - max_s)
					max_k -= 1
				else:
					p += abs(a[i] - min_s)
					min_k -= 1
			res.append(p // 2)
	print(min(res))


n = int(input())
a = list(map(int, input().strip().split()))
a.sort(reverse=True)
s = sum(a)
k = s // n
j = s - n * k
d = 0
for i in range(len(a)):
	if i < j:
		d += abs(a[i] - k - 1)
	else:
		d += abs(a[i] - k)
print(d // 2)


import math

def average(args):
	sum = 0
	count = 0
	for arg in args:
		sum += arg
		count += 1
	if count > 0:
		sum = sum / count
	return sum
n = int(input())
args = [int(x) for x in input().split()]
avg = average(args)
up = 0
down = 0
for arg in args:
	if arg > avg:
		down += arg - math.ceil(avg)
	elif arg < avg:
		up += math.floor(avg) - arg
print(max(up, down))


for _ in range(1):
	n = int(input())
	l = list(map(int, input().split()))
	s = sum(l) // n
	t = sum(l) % n
	arr = [sum(l) // n] * n
	for i in range(len(arr)):
		if t > 0:
			arr[i] += 1
			t -= 1
	arr.sort()
	l.sort()
	ans = 0
	for i in range(n):
		ans += abs(arr[i] - l[i])
	print(ans // 2)


import os
import sys
from io import BytesIO, IOBase

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
BUFSIZE = 8192
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
rstr = lambda : input().strip()
rstrs = lambda : [str(x) for x in input().split()]
rstr_2d = lambda n: [rstr() for _ in range(n)]
rint = lambda : int(input())
rints = lambda : [int(x) for x in input().split()]
rint_2d = lambda n: [rint() for _ in range(n)]
rints_2d = lambda n: [rints() for _ in range(n)]
ceil1 = lambda a, b: (a + b - 1) // b
(n, a) = (rint(), sorted(rints()))
(su, ans, be) = (sum(a), 0, 0)
(div, mod) = divmod(su, n)
for j in range(n - 1, -1, -1):
	ext = n - j <= mod
	while a[j] > div + ext:
		(rem0, rem1) = (div + ext - a[be], a[j] - div - ext)
		if rem0 < rem1:
			a[j] -= rem0
			be += 1
			ans += rem0
		elif rem1 == rem0:
			ans += rem0
			be += 1
			break
		else:
			ans += rem1
			a[be] += rem1
			break
print(ans)


import sys

def get_array():
	return list(map(int, sys.stdin.readline().split()))

def get_ints():
	return map(int, sys.stdin.readline().split())

def input():
	return sys.stdin.readline().strip('\n')
n = int(input())
l = get_array()
l.sort()
k = sum(l)
nw = [k // n] * n
k %= n
for i in range(k):
	nw[i] += 1
nw = nw[::-1]
ans = 0
for i in range(n):
	ans += abs(l[i] - nw[i])
print(ans // 2)


def scan_int_ln():
	return [int(x) for x in input().split()]
n = int(input())
m = scan_int_ln()
avg = sum(m) / len(m)
time = 0
m.sort()
if avg == int(avg):
	avg = int(avg)
	for x in m:
		time += abs(avg - x)
else:
	higher_n = sum(m) % n
	lower_n = n - higher_n
	mm = [int(avg)] * lower_n + [int(avg) + 1] * higher_n
	for (x, y) in zip(m, mm):
		time += abs(y - x)
time //= 2
print(time)


import sys
import os.path
from collections import *
import math
import bisect
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	input = sys.stdin.readline
n = int(input())
arr = [int(x) for x in input().split()]
arr.sort()
tot = sum(arr)
x = tot // n
rem = tot % n
arr1 = [x] * n
for i in range(rem):
	arr1[n - i - 1] += 1
res = 0
for i in range(n):
	res += abs(arr[i] - arr1[i])
print(res // 2)


n = int(input())
servers = list(map(int, input().split()))
servers.sort()
avg = sum(servers) / n
above = 0
below = 0
for serve in servers:
	if serve < avg:
		above += (avg - serve) // 1
	elif serve > avg:
		below += (serve - avg) // 1
print(int(max(above, below)))


n = int(input())
queries = sorted(list(map(int, input().split())))
desired = [sum(queries) // n] * (n - sum(queries) % n)
desired.extend([sum(queries) // n + 1] * (sum(queries) % n))
time = 0
for i in range(n):
	time += abs(queries[i] - desired[i])
time //= 2
print(time)


import sys
from math import *

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())
n = mint()
m = list(mints())
a = [0] * 20002
s = 0
for i in m:
	a[i] += 1
	s += i
b = s // n
c = s % n
j = 20001
r = 0
for i in range(20002):
	while a[i] > 0 and (j > b + 1 or (j == b + 1 and a[j] > c)):
		if a[j] == 0:
			j -= 1
		else:
			z = min(a[i], a[j])
			a[i + 1] += z
			a[i] -= z
			a[j] -= z
			a[j - 1] += z
			r += z
print(r)


n = int(input())
l = list(map(int, input().split()))
s = sum(l)
lo = s // n
hi = s // n + 1
lo_n = -1
for i in range(len(l) + 1):
	if lo * i + hi * (len(l) - i) == s:
		lo_n = i
		break
if lo_n < 0 or lo_n > len(l):
	assert False
hi_n = n - lo_n
l = sorted(l)
l2 = []
for i in range(lo_n):
	l2.append(lo)
for i in range(hi_n):
	l2.append(hi)
ans = 0
for i in range(len(l)):
	ans += abs(l[i] - l2[i])
print(ans // 2)


n = int(input())
arr = list(map(int, input().split()))
assert len(arr) == n
total = sum(arr)
avg1 = total // n
avg2 = avg1 + (0 if total % n == 0 else 1)
seconds = 0
offset = 0
for n in arr:
	if n < avg1:
		seconds += avg1 - n
		offset += avg1 - n
	elif n > avg2:
		seconds += n - avg2
		offset += avg2 - n
seconds = (seconds + abs(offset)) // 2
print(seconds)


n = int(input())
m = list(map(int, input().split()))
ss = sum(m)
dd = ss // n
maxdd = ss % n
mindd = n - maxdd
ans = 0
for a in m:
	if a >= dd and maxdd == 0:
		ans += a - dd
		mindd -= 1
	elif a > dd:
		if maxdd > 0:
			ans += a - (dd + 1)
			maxdd -= 1
		else:
			ans + +a - dd
			mindd -= 1
print(ans)


N = int(input())
A = list(map(int, input().split()))
s = sum(A)
ma = -(-s // N)
mb = s // N
B = [mb] * (N - s % N) + [ma] * (s % N)
A.sort()
res = 0
for i in range(N):
	if A[i] < B[i]:
		res += B[i] - A[i]
print(res)


a = input()
l = list(map(int, input().split()))
avg = 0
s1 = 0
s2 = 0
for i in l:
	avg += i
avg /= len(l)
for i in l:
	if i < avg:
		s1 += int(abs(i - avg))
	else:
		s2 += int(abs(i - avg))
print(int(max(s1, s2)))