#include <bits/stdc++.h>
template <class T>
void rd(T& ret) {
  ret = 0;
  bool ok = 0, u = 0;
  for (;;) {
    int c = getchar();
    if (c >= '0' && c <= '9')
      ret = (ret << 3) + (ret << 1) + c - '0', ok = 1;
    else if (c == '-')
      u = 1;
    else if (ok) {
      if (u) ret *= -1;
      return;
    }
  }
}
long long pow_mod(long long p, long long n, long long mod) {
  long long ret = 1;
  for (; n; n >>= 1) {
    if (n & 1) ret = ret * p % mod;
    p = p * p % mod;
  }
  return ret;
}
template <class T>
bool chmin(T& a, const T& b) {
  return b < a ? a = b, 1 : 0;
}
template <class T>
bool chmax(T& a, const T& b) {
  return b > a ? a = b, 1 : 0;
}
using namespace std;
int main() {
  int n;
  cin >> n;
  vector<int> vec(n);
  for (int i = 0; i < n; ++i) {
    cin >> vec[i];
  }
  vector<pair<int, int> > stk;
  for (int i = 0; i < n; ++i) {
    pair<int, int> last(vec[i], i);
    while (!stk.empty() && stk.back().first > last.first) {
      vector<int> v(vec.begin() + stk.back().second, vec.begin() + i + 1);
      nth_element(v.begin(), v.begin() + (((int)(v).size()) >> 1), v.end());
      last = pair<int, int>(v[((int)(v).size()) >> 1], stk.back().second);
      stk.pop_back();
    }
    stk.push_back(last);
  }
  long long res = 0;
  stk.push_back(pair<int, int>(0, n));
  for (int i = 0; i < ((int)(stk).size()) - 1; ++i) {
    for (int j = stk[i].second; j < stk[i + 1].second; ++j) {
      res += abs(stk[i].first - vec[j]);
    }
  }
  cout << res;
  return 0;
}
