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.

Difficulty: MEDIUM

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)


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)


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())
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())
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)))


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 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)


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)))