import sys

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

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

sys.setrecursionlimit(10**9)



N = int(eval(input()))

As = list(mapint())

As.sort(reverse=True)

from heapq import heappush, heappop



first = (As.pop(0))

hq = []

if N<2:

    print((0))

else:

    ans = 0

    second = As.pop(0)

    ans += first

    heappush(hq, (-second, -first))

    heappush(hq, (-second, -first))

    for a in As:

        s, f = heappop(hq)

        ans -= s

        heappush(hq, (-a, s))

        heappush(hq, (-a, f))



print(ans)
import sys

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

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

sys.setrecursionlimit(10**9)



N = int(eval(input()))

As = list(mapint())



conf = 0

from heapq import heapify, heappop, heappush

As.sort(reverse=True)

m = As.pop(0)

s = As.pop(0)

conf += m

Q = []

heappush(Q, -s)

heappush(Q, -s)

for a in As:

    s = heappop(Q)

    conf -= s

    heappush(Q, -a)

    heappush(Q, -a)

print(conf)
import sys


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


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


sys.setrecursionlimit(10**9)
N = int(eval(input()))
As = list(mapint())
As.sort(reverse=True)
from heapq import heappush, heappop

first = As.pop(0)
hq = []
if N < 2:
    print((0))
else:
    ans = 0
    second = As.pop(0)
    ans += first
    heappush(hq, (-second, -first))
    heappush(hq, (-second, -first))
    for a in As:
        s, f = heappop(hq)
        ans -= s
        heappush(hq, (-a, s))
        heappush(hq, (-a, f))
print(ans)

import sys


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


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


sys.setrecursionlimit(10**9)
N = int(eval(input()))
As = list(mapint())
conf = 0
from heapq import heapify, heappop, heappush

As.sort(reverse=True)
m = As.pop(0)
s = As.pop(0)
conf += m
Q = []
heappush(Q, -s)
heappush(Q, -s)
for a in As:
    s = heappop(Q)
    conf -= s
    heappush(Q, -a)
    heappush(Q, -a)
print(conf)

+conf = 0 +from heapq import heapify, heappop, heappush + -from heapq import heappush, heappop - -first = As.pop(0) -hq = [] -if N < 2: -    print((0)) -else: -    ans = 0 -    second = As.pop(0) -    ans += first -    heappush(hq, (-second, -first)) -    heappush(hq, (-second, -first)) -    for a in As: -        s, f = heappop(hq) -        ans -= s -        heappush(hq, (-a, s)) -        heappush(hq, (-a, f)) -print(ans) +m = As.pop(0) +s = As.pop(0) +conf += m +Q = [] +heappush(Q, -s) +heappush(Q, -s) +for a in As: +    s = heappop(Q) +    conf -= s +    heappush(Q, -a) +    heappush(Q, -a) +print(conf)