#include <bits/stdc++.h>
using namespace std;
int main() {
  long long n;
  scanf("%I64d", &n);
  vector<long long> arr(n), s;
  for (long long i = 0; i < n; i++) {
    scanf("%I64d", &arr[i]);
    s.push_back(arr[i]);
  }
  sort(s.begin(), s.end());
  s.erase(unique(s.begin(), s.end()), s.end());
  vector<long long> dp(s.size(), 0);
  for (int i = 0; i < n; i++) {
    dp[0] += llabs(s[0] - arr[i]);
    for (int j = 1; j < s.size(); j++) {
      dp[j] = min(dp[j - 1], dp[j] + llabs(arr[i] - s[j]));
    }
  }
  long long res = dp[0];
  for (long long i = 1; i < s.size(); i++) res = min(res, dp[i]);
  printf("%I64d\n", res);
}
