#include <bits/stdc++.h>
using namespace std;
template <class c>
struct rge {
  c b, e;
};
template <class c>
rge<c> range(c i, c j) {
  return rge<c>{i, j};
}
template <class c>
auto dud(c* x) -> decltype(cerr << *x, 0);
template <class c>
char dud(...);
struct debug {
  template <class c>
  debug& operator<<(const c&) {
    return *this;
  }
};
using ll = long long;
using ld = long double;
constexpr int nax = 1000 * 1000 + 105;
constexpr int infty = 1000 * 1000 * 1000 + 5;
constexpr int mod = 1000 * 1000 * 1000 + 7;
int n, m;
vector<int> nums;
vector<int> a;
vector<vector<ll>> dp;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> n;
  a.push_back(-infty);
  nums.push_back(-infty);
  for (int i = 0; i < n; i++) {
    int x;
    cin >> x;
    a.push_back(x);
    nums.push_back(x);
  }
  sort(nums.begin(), nums.end());
  nums.resize(unique(nums.begin(), nums.end()) - nums.begin());
  m = (int)nums.size();
  dp.resize(4);
  dp[0].resize(m, 0);
  for (int i = 1; i <= n; i++) {
    dp[i % 4].resize(m);
    for (int j = 0; j < m; j++) {
      dp[i % 4][j] = dp[(i - 1 + 4) % 4][j] + abs(a[i] - nums[j]);
      if (j > 0) {
        dp[i % 4][j] = min(dp[i % 4][j], dp[i % 4][j - 1]);
      }
    }
  }
  cout << dp[n % 4][m - 1] << endl;
  return 0;
}
