#include <bits/stdc++.h>
using namespace std;
const int MAXN = 3e5 + 10;
int N;
int arr[MAXN];
int vis[MAXN];
struct comp {
  bool operator()(int x, int y) {
    return arr[x] > arr[y] || (arr[x] == arr[y] && x < y);
  }
};
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  memset(vis, 0, sizeof vis);
  cin >> N;
  for (int i = 1; i <= N; i++) cin >> arr[i];
  long long ans = 0, cnt = 0;
  priority_queue<int, vector<int>, comp> que;
  for (int i = 1; i <= N; i++) {
    if (que.empty() || arr[i] < arr[que.top()])
      que.push(i);
    else {
      int tp = que.top();
      que.pop();
      ans += arr[i] - arr[tp];
      vis[i]++, cnt++;
      if (++vis[tp] >= 2) cnt--, vis[tp] = 0;
      que.push(i), que.push(i);
    }
  }
  cout << ans << endl;
  return 0;
}
