/*
贪心来选择, 如果能找到比当前小的, 就用最小的来更新当前的
优先队列即可
*/
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<iostream>
#define ll long long
#define mmp make_pair
#define M
using namespace std;
int read()
{
int nm = 0, f = 1;
char c = getchar();
for(; !isdigit(c); c = getchar()) if(c == '-') f = -1;
for(; isdigit(c); c = getchar()) nm = nm * 10 + c - '0';
return nm * f;
}
priority_queue<ll> q;
ll ans = 0;
int main()
{
int n = read();
while(n--)
{
int x = read();
q.push(-x), q.push(-x);
ans += x + q.top();
q.pop();
}
cout << ans << "\n";
return 0;
}