#include<bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
vector<int> p(n);
for(int i = 0; i < n; ++i){
cin >> p[i];
}
long long ans = 0;
priority_queue<pair<int,int>> pq;
for(int i = n-1; i >= 0; --i){
if(pq.empty()) pq.push({p[i],-1});
else {
if(pq.top().first > p[i]) {
auto x = pq.top();
pq.pop();
ans += x.first - p[i];
if(x.second != -1) {
pq.push({x.first, -1});
}
pq.push({p[i],1});
}
else {
pq.push({p[i],-1});
}
}
}
cout << ans << endl;
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCmludCBtYWluKCl7Cglpb3M6OnN5bmNfd2l0aF9zdGRpbygwKTsKCWNpbi50aWUoMCk7CglpbnQgbjsKCWNpbiA+PiBuOwoJdmVjdG9yPGludD4gcChuKTsKCWZvcihpbnQgaSA9IDA7IGkgPCBuOyArK2kpewoJCWNpbiA+PiBwW2ldOwoJfQoJbG9uZyBsb25nIGFucyA9IDA7Cglwcmlvcml0eV9xdWV1ZTxwYWlyPGludCxpbnQ+PiBwcTsKCWZvcihpbnQgaSA9IG4tMTsgaSA+PSAwOyAtLWkpewoJCWlmKHBxLmVtcHR5KCkpIHBxLnB1c2goe3BbaV0sLTF9KTsKCQllbHNlIHsKCQkJaWYocHEudG9wKCkuZmlyc3QgPiBwW2ldKSB7CgkJCQlhdXRvIHggPSBwcS50b3AoKTsKCQkJCXBxLnBvcCgpOwoJCQkJYW5zICs9IHguZmlyc3QgIC0gcFtpXTsKCQkJCWlmKHguc2Vjb25kICE9IC0xKSB7CgkJCQkJcHEucHVzaCh7eC5maXJzdCwgLTF9KTsKCQkJCX0KCQkJCXBxLnB1c2goe3BbaV0sMX0pOwoJCQl9CgkJCWVsc2UgewoJCQkJcHEucHVzaCh7cFtpXSwtMX0pOwoJCQl9CgkJfQoJfQoJY291dCA8PCBhbnMgPDwgZW5kbDsKfQ==