#include <bits/stdc++.h>
using namespace std;
template <typename C>
auto test(C* x) -> decltype(cerr << *x, 0LL);
template <typename C>
char test(...);
template <typename C>
struct itr {
  C begin, end;
};
template <typename C>
itr<C> get_range(C b, C e) {
  return itr<C>{b, e};
};
struct debug {
  template <typename T>
  debug& operator<<(const T&) {
    return *this;
  }
};
string _ARR_(int* arr, int sz) {
  string ret = "{ " + to_string(arr[0]);
  for (int i = 1; i < sz; i++) ret += " , " + to_string(arr[i]);
  ret += " }";
  return ret;
}
const long long INF = 1e18 + 7;
const int MxN = 5010;
long long dp[2][MxN];
inline long long d(int x, int y) { return abs(x - y); }
int main(void) {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int n;
  cin >> n;
  vector<long long> a(n), b(n);
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    b[i] = a[i];
  }
  sort(b.begin(), b.end());
  int cur = 1;
  dp[cur][0] = d(a[0], b[0]);
  for (int i = 1; i < n; i++) {
    dp[cur][i] = min(dp[cur][i - 1], d(a[0], b[i]));
  }
  for (int i = 1; i < n; i++) {
    cur = !cur;
    dp[cur][0] = d(a[i], b[0]) + dp[!cur][0];
    for (int j = 1; j < n; j++) {
      dp[cur][j] = min(dp[cur][j - 1], dp[!cur][j] + d(a[i], b[j]));
    }
  }
  cout << dp[cur][n - 1] << '\n';
  return 0;
}
