#include <bits/stdc++.h>
using namespace std;
const long long LLINF = 1000000000LL * 1000000000LL;
const int MAXN = 5010;
map<int, int> mp;
int a[MAXN], b[MAXN], id2real[MAXN], id[MAXN];
long long dp[2][MAXN];
int main() {
  int n;
  while (scanf("%d", &n) != EOF) {
    mp.clear();
    int i, j;
    for (i = 0; i < n; i++) {
      scanf("%d", &a[i]);
      b[i] = a[i];
    }
    sort(b, b + n);
    int K = (int*)unique(b, b + n) - b;
    for (i = 0; i < K; i++) {
      id2real[i] = b[i];
      mp[b[i]] = i;
    }
    for (i = 0; i < n; i++) id[i] = mp[a[i]];
    memset(dp, 0x3f, sizeof(dp));
    for (i = 0; i < K; i++) {
      dp[0][i] = ((id2real[i] - a[0]) >= 0 ? (id2real[i] - a[0])
                                           : (-(id2real[i] - a[0])));
    }
    int from, to;
    from = 0;
    to = 1;
    for (i = 0; i < n - 1; i++) {
      for (j = 1; j < K; j++)
        if (dp[from][j] > dp[from][j - 1]) dp[from][j] = dp[from][j - 1];
      memset(&dp[to][0], 0x3f, sizeof(dp[0]));
      for (j = 0; j < K; j++) {
        if (a[i + 1] >= id2real[j])
          if (dp[to][id[i + 1]] > dp[from][j]) dp[to][id[i + 1]] = dp[from][j];
        int tcost = ((id2real[j] - a[i + 1]) >= 0 ? (id2real[j] - a[i + 1])
                                                  : (-(id2real[j] - a[i + 1])));
        if (dp[to][j] > dp[from][j] + tcost) dp[to][j] = dp[from][j] + tcost;
      }
      from = 1 - from;
      to = 1 - to;
    }
    long long best = LLINF;
    for (i = 0; i < K; i++)
      if (dp[from][i] < best) best = dp[from][i];
    cout << best << endl;
  }
  return 0;
}
