#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
#define x first
#define y second
const int N=1e6+10,mod=998244353,INF=1e17,M=5e6;
typedef pair<int,int> PII;
void slove(){
int n;
cin>>n;
priority_queue<int,vector<int>,greater<int>> heap;
int x;cin>>x;heap.push(x);
int ans=0;
for(int i=2;i<=n;i++){
cin>>x;
int t=heap.top();
if(x>t) ans+=x-t,heap.pop(),heap.push(x);//x是反悔的物品
heap.push(x);//本身就可以选择的物品
/*
若x被纳入了反悔的物品,并且在nx的时候用上了,那么就是(nx-x)
而x-t,这样的话对答案的贡献就是(nx-x+(x-t)),即nx-t
也就是说讲买入t,卖出x,转化为买入t,卖出nx
也就是没有选择x,这个也显然被考虑到堆中去了
*/
}
cout<<ans<<endl;
}
signed main(){
ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
int T=1;
// cin>>T;
while(T--) slove();
}