#include <bits/stdc++.h>
using namespace std;
template <class T>
inline string itos(T n) {
  return (n) < 0    ? "-" + itos(-(n))
         : (n) < 10 ? (string)("") + (char)('0' + (n))
                    : itos((n) / 10) + itos((n) % 10);
}
int a[5010], b[5010];
long long dp[2][5010];
int main(void) {
  int N, i, j;
  cin >> N;
  for ((i) = 0; (i) < (int)(N); (i)++) cin >> a[i];
  for ((i) = 0; (i) < (int)(N); (i)++) b[i] = a[i];
  sort(b, b + N);
  for ((i) = 0; (i) < (int)(N); (i)++) dp[0][i] = abs(a[0] - b[i]);
  for ((i) = 0; (i) < (int)(N - 1); (i)++) {
    int cur = i % 2, next = (i + 1) % 2;
    long long small = (1ll << 60);
    for ((j) = 0; (j) < (int)(N); (j)++) {
      small = min(small, dp[cur][j]);
      dp[next][j] = abs(a[i + 1] - b[j]) + small;
    }
  }
  long long ans = (1ll << 60);
  for ((i) = 0; (i) < (int)(N); (i)++) ans = min(ans, dp[(N - 1) % 2][i]);
  cout << ans << endl;
  return 0;
}
