#include <bits/stdc++.h>
#define mp make_pair
#define pb push_back
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef long double ld;
typedef map<pii,set<pii> >::iterator mapit;
typedef multiset<ll>::iterator setit;
const int maxn = 1e5 + 5;
const int maxlog = 20;
const ll mod = 1e9 + 7;
const int sq = 340;
const int inf = 1e9 + 43;
const ld pi = 3.14159265;
int n ;
multiset<int> notused , usedmax ;
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin >> n;
ll ans = 0;
for(int i = 1 ; i <= n ; i ++ ){
int x ;
cin >> x;
int m1 = inf , m2 = inf;
if(notused.size() != 0){
m1 = *notused.begin();
}
if(usedmax.size() != 0)
m2 = *usedmax.begin();
if(m1 < m2){
if(x > m1){
notused.erase(notused.begin());
usedmax.insert(x);
ans += (ll) (x - m1);
}
else
notused.insert(x);
}
else{
if(x > m2){
usedmax.erase(usedmax.begin());
usedmax.insert(x);
notused.insert(m2);
ans += (ll) (x - m2);
}
else
notused.insert(x);
}
}
cout << ans ;
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CiNkZWZpbmUgbXAgbWFrZV9wYWlyCiNkZWZpbmUgcGIgcHVzaF9iYWNrCgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKdHlwZWRlZiBsb25nIGxvbmcgbGw7CnR5cGVkZWYgcGFpcjxpbnQsaW50PiBwaWk7CnR5cGVkZWYgbG9uZyBkb3VibGUgbGQ7CnR5cGVkZWYgbWFwPHBpaSxzZXQ8cGlpPiA+OjppdGVyYXRvciBtYXBpdDsKdHlwZWRlZiBtdWx0aXNldDxsbD46Oml0ZXJhdG9yIHNldGl0OwoKY29uc3QgaW50IG1heG4gPSAxZTUgKyA1Owpjb25zdCBpbnQgbWF4bG9nID0gMjA7CmNvbnN0IGxsIG1vZCA9IDFlOSArIDc7CmNvbnN0IGludCBzcSA9IDM0MDsKY29uc3QgaW50IGluZiA9IDFlOSArIDQzOwpjb25zdCBsZCBwaSA9IDMuMTQxNTkyNjU7CmludCBuIDsKbXVsdGlzZXQ8aW50PiBub3R1c2VkICwgdXNlZG1heCA7CmludCBtYWluKCkKewogICAgaW9zX2Jhc2U6OnN5bmNfd2l0aF9zdGRpbygwKTtjaW4udGllKDApO2NvdXQudGllKDApOwogICAgY2luID4+IG47CiAgICBsbCBhbnMgPSAwOwogICAgZm9yKGludCBpID0gMSA7IGkgPD0gbiA7IGkgKysgKXsKICAgICAgICBpbnQgeCA7CiAgICAgICAgY2luID4+IHg7CiAgICAgICAgaW50IG0xID0gaW5mICwgbTIgPSBpbmY7CiAgICAgICAgaWYobm90dXNlZC5zaXplKCkgIT0gMCl7CiAgICAgICAgICAgIG0xID0gKm5vdHVzZWQuYmVnaW4oKTsKICAgICAgICB9CiAgICAgICAgaWYodXNlZG1heC5zaXplKCkgIT0gMCkKICAgICAgICAgICAgbTIgPSAqdXNlZG1heC5iZWdpbigpOwogICAgICAgIGlmKG0xIDwgbTIpewogICAgICAgICAgICBpZih4ID4gbTEpewogICAgICAgICAgICAgICAgbm90dXNlZC5lcmFzZShub3R1c2VkLmJlZ2luKCkpOwogICAgICAgICAgICAgICAgdXNlZG1heC5pbnNlcnQoeCk7CiAgICAgICAgICAgICAgICBhbnMgKz0gKGxsKSAoeCAtIG0xKTsKICAgICAgICAgICAgfQogICAgICAgICAgICBlbHNlCiAgICAgICAgICAgICAgICBub3R1c2VkLmluc2VydCh4KTsKICAgICAgICB9CiAgICAgICAgZWxzZXsKICAgICAgICAgICAgaWYoeCA+IG0yKXsKICAgICAgICAgICAgICAgIHVzZWRtYXguZXJhc2UodXNlZG1heC5iZWdpbigpKTsKICAgICAgICAgICAgICAgIHVzZWRtYXguaW5zZXJ0KHgpOwogICAgICAgICAgICAgICAgbm90dXNlZC5pbnNlcnQobTIpOwogICAgICAgICAgICAgICAgYW5zICs9IChsbCkgKHggLSBtMik7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgZWxzZQogICAgICAgICAgICAgICAgbm90dXNlZC5pbnNlcnQoeCk7CiAgICAgICAgfQogICAgfQogICAgY291dCA8PCBhbnMgOwogICAgcmV0dXJuIDA7Cn0=