#include <bits/stdc++.h>
using namespace std;
long long const inf = LONG_LONG_MAX;
int main() {
  long long n;
  cin >> n;
  vector<long long> a(n, 0);
  for (int i = 0; i < n; ++i) cin >> a[i];
  vector<long long> b;
  set<long long> st;
  for (int i = 0; i < n; ++i) {
    if (st.count(a[i]) == 0) {
      b.push_back(a[i]);
      st.insert(a[i]);
    }
  }
  long long m = b.size();
  sort(b.begin(), b.end());
  vector<long long> dp[2];
  long long source = 0, dest = 1;
  dp[source].assign(n + 1, 0);
  dp[dest].assign(n + 1, inf);
  dp[source][0] = abs(a[0] - b[0]);
  for (int j = 1; j < m; ++j) {
    dp[source][j] = min(dp[source][j - 1], abs(a[0] - b[j]));
  }
  for (int i = 1; i < n; ++i) {
    dp[dest][0] = dp[source][0] + abs(a[i] - b[0]);
    for (int j = 1; j < m; ++j) {
      dp[dest][j] = min(dp[dest][j - 1], dp[source][j] + abs(a[i] - b[j]));
    }
    dest ^= 1;
    source ^= 1;
  }
  long long mini = inf;
  for (int j = 0; j < m; ++j) {
    if (dp[source][j] < mini) {
      mini = dp[source][j];
    }
  }
  cout << mini << endl;
}
