#include <bits/stdc++.h>
using namespace std;
const long long inf = 1ll << 62;
long long dp[2][5007], a[5007], b[5007];
long long min(long long a, long long b) { return a < b ? a : b; }
int main() {
  long long n;
  while (scanf("%I64d", &n) != EOF) {
    for (int i = 1; i <= n; i++) {
      scanf("%I64d", &a[i]);
      b[i] = a[i];
    }
    sort(b + 1, b + n + 1);
    int tot = unique(b + 1, b + n + 1) - b - 1;
    dp[1][1] = inf;
    for (int i = 1; i <= tot; i++) {
      dp[1 & 1][i] = fabs(b[i] - a[1]);
      dp[2 & 1][i] = inf;
    }
    for (int i = 2; i <= n; i++) {
      long long minn = inf;
      for (int j = 1; j <= tot; j++) {
        minn = min(minn, dp[(i - 1) & 1][j]);
        dp[i & 1][j] = min(dp[i & 1][j], minn + fabs(b[j] - a[i]));
      }
      for (int j = 1; j <= tot; j++) dp[(i + 1) & 1][j] = inf;
    }
    long long ans = inf;
    for (int i = 1; i <= tot; i++) ans = min(ans, dp[n & 1][i]);
    printf("%I64d\n", ans);
  }
  return 0;
}
