#include <bits/stdc++.h>
using namespace std;
const int INFint = 2e9;
const long long INF = 1e18;
const long long MOD = 1000000007ll;
int main() {
  ios_base::sync_with_stdio(0);
  int n;
  cin >> n;
  vector<long long> a(n), b;
  for (auto &x : a) cin >> x;
  b = a;
  sort(b.begin(), b.end());
  b.resize(unique(b.begin(), b.end()) - b.begin());
  vector<long long> dp[2];
  dp[0].resize(b.size(), INF);
  dp[1].resize(b.size(), INF);
  dp[0][0] = abs(a[0] - b[0]);
  for (int i = 1; i < b.size(); i++) {
    dp[0][i] = min(dp[0][i - 1], abs(b[i] - a[0]));
  }
  int e = 1;
  for (int i = 1; i < n; i++) {
    dp[e][0] = dp[e ^ 1][0] + abs(a[i] - b[0]);
    for (int j = 1; j < b.size(); j++) {
      dp[e][j] = min(dp[e][j - 1], dp[e ^ 1][j] + abs(a[i] - b[j]));
    }
    e ^= 1;
  }
  cout << dp[e ^ 1][b.size() - 1];
  fprintf(stderr, "\nTIME = %lf\n", 1.0 * clock() / CLOCKS_PER_SEC);
  ;
  return 0;
}
