n=int(input()) X=10**20 from heapq import heappush,heappop sm=0 sl=[X]*n sr=[-X]*n sla=0 sra=0 def addl(p): global sm,sl,sr,sla,sra if p<=sr[0]+sra: heappush(sl,-(p-sla)) else: sm+=p-sr[0]-sra heappush(sl,-(heappop(sr)+sra-sla)) heappush(sr,p-sra) return def addr(p): global sm,sl,sr,sla,sra if -sl[0]+sla<=p: heappush(sr,p-sra) else: sm+=-sl[0]+sla-p heappush(sr,-heappop(sl)+sla-sra) heappush(sl,-(p-sla)) return a=list(map(int,input().split())) a.sort() for v in a: sr=[X] sla+=1 addl(v) addr(v) print(sm)