#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int _inf = 0xc0c0c0c0;
const long long INF = 0x3f3f3f3f3f3f3f3f;
const long long _INF = 0xc0c0c0c0c0c0c0c0;
const long long mod = (int)1e9 + 7;
const int N = 5e3 + 100;
long long dp[2][N];
int a[N];
int b[N];
int Ac() {
  int n;
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) {
    scanf("%d", &a[i]);
    b[i] = a[i];
  }
  sort(b + 1, b + 1 + n);
  int pre = 1, now = 0;
  for (int i = 1; i <= n; ++i) {
    long long Mn = INF;
    swap(pre, now);
    for (int j = 1; j <= n; ++j) {
      Mn = min(Mn, dp[pre][j]);
      dp[now][j] = Mn + abs(a[i] - b[j]);
    }
  }
  long long Mn = INF;
  for (int i = 1; i <= n; ++i) Mn = min(Mn, dp[now][i]);
  cout << Mn << endl;
  return 0;
}
int main() {
  Ac();
  return 0;
}
