#include <bits/stdc++.h>
using namespace std;
const int maxm = 1000 + 5;
const int maxn = 1000 + 5;
const int mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const double eps = 1e-8;
void debug() { printf("error\n"); }
int main() {
  int n;
  scanf("%d", &n);
  int a;
  long long ans = 0;
  priority_queue<int> q;
  for (int i = 0; i < n; i++) {
    scanf("%d", &a);
    ans += a;
    q.push(-a), q.push(-a);
    ans += q.top();
    q.pop();
  }
  printf("%lld", ans);
  return 0;
}
