#include <bits/stdc++.h>
using namespace std;
const int N = 5e3 + 10;
int n;
int a[N];
const long long oo = 0x3f3f3f3f;
vector<int> vec;
map<int, int> id;
int getId(int x) {
  return lower_bound(vec.begin(), vec.end(), x) - vec.begin();
}
long long dp[2][N];
int m;
void update(int cur) {
  long long pre = dp[cur][0];
  for (int i = 0; i < m; i++) {
    pre = min(pre, dp[cur][i]);
    dp[cur][i] = pre;
  }
}
int main() {
  while (cin >> n) {
    for (int i = 0; i < n; i++) {
      cin >> a[i];
      vec.push_back(a[i]);
    }
    sort(vec.begin(), vec.end());
    for (int i = 0; i < n; i++) {
      id[a[i]] = getId(a[i]);
    }
    m = vec.size();
    int cur = 0;
    for (int i = 0; i < m; i++) {
      dp[cur][i] = abs(vec[i] - a[0]);
    }
    update(cur);
    for (int i = 1; i < n; i++) {
      for (int j = 0; j < m; j++) {
        dp[cur ^ 1][j] = dp[cur][j] + abs(vec[j] - a[i]);
      }
      cur ^= 1;
      update(cur);
    }
    long long res = dp[cur][0];
    for (int i = 0; i < m; i++) {
      res = min(res, dp[cur][i]);
    }
    cout << res << endl;
  }
  return 0;
}
