#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int N = 1e6 + 5;
long long int A[N], B[N];
int main(int argc, char const *argv[]) {
  cin.sync_with_stdio(0);
  cin.tie(0);
  int n;
  cin >> n;
  set<int> S;
  for (int i = 1; i <= n; i++) {
    cin >> A[i];
    S.insert(A[i]);
  }
  int m = 0;
  for (auto v : S) B[++m] = v;
  vector<long long int> curr(m + 1), prev(m + 1);
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (i == 1 && j == 1)
        curr[j] = abs(A[1] - B[1]);
      else if (j == 1)
        curr[j] = prev[j] + abs(A[i] - B[1]);
      else if (i == 1)
        curr[j] = min(curr[j - 1], abs(A[1] - B[j]));
      else
        curr[j] = min(prev[j] + abs(B[j] - A[i]), curr[j - 1]);
    }
    prev = curr;
  }
  cout << curr[m] << '\n';
  return 0;
}
