#include <bits/stdc++.h>
using namespace std;
const long long inf = 9.2e18;
const int maxn = 300007;
const int INF = 2.1e9;
const int MOD = 1e9 + 7;
const double dif = 1e-7;
const double PI = acos(-1.0);
int n, m, k, x;
long long a[maxn];
priority_queue<int, vector<int>, greater<int> > Q;
long long solve1() {
  long long ans = 0;
  while (!Q.empty()) Q.pop();
  for (int i = 1; i <= n; i++) {
    Q.push(a[i]);
    if (Q.top() < a[i]) {
      ans += a[i] - Q.top();
      Q.pop();
      Q.push(a[i]);
    }
  }
  return ans;
}
long long dp[1000][1000];
long long solve2() {
  for (int i = 0; i <= n + 1; i++) {
    for (int j = 0; j <= n; j++) {
      dp[i][j] = -INF;
    }
  }
  dp[n + 1][0] = 0;
  for (int i = n; i >= 1; i--) {
    for (int j = 0; j < n; j++) {
      dp[i][j] = max(dp[i + 1][j], dp[i + 1][j + 1] - a[i]);
      if (j) dp[i][j] = max(dp[i][j], dp[i + 1][j - 1] + a[i]);
    }
  }
  return dp[1][0];
}
void check(int n, int x, int k) {
  srand(time(NULL));
  int flag = 1;
  while (k--) {
    for (int i = 1; i <= n; i++) a[i] = rand() % x;
    long long ans1 = solve1();
    long long ans2 = solve2();
    if (ans1 != ans2) {
      flag = 0;
      cout << ans1 << ' ' << ans2 << endl;
      for (int i = 1; i <= n; i++) cout << a[i] << ' ';
      cout << endl;
      break;
    }
  }
  if (flag) cout << "YES" << endl;
}
int main() {
  while (cin >> n) {
    while (!Q.empty()) Q.pop();
    for (int i = 1; i <= n; i++) {
      cin >> a[i];
    }
    long long ans = solve1();
    cout << ans << endl;
  }
  return 0;
}
