#include <bits/stdc++.h>
using namespace std;
unsigned long long N;
unsigned long long x;
priority_queue<unsigned long long, vector<unsigned long long>,
               greater<unsigned long long> >
    pq;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  unsigned long long ans = 0;
  cin >> N;
  for (unsigned long long i = 0; i < N; i++) {
    cin >> x;
    ans += x;
    pq.push(x);
    pq.push(x);
    ans -= pq.top();
    pq.pop();
  }
  cout << ans << endl;
}
