#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;
}