n = int(input()) y = tuple(map(int, input().split())) m = {} def f(a): if a not in m: cnt = 0 for b in y: cnt += abs(b - a) m[a] = cnt return m[a] l = min(y) r = max(y) while r - l > 2: if f(l) > f(r): l = (l * 2 + r) // 3 else: r = (l + r * 2) // 3 print(min(f(l), f(l + 1), f(l + 2)))