#include <bits/stdc++.h>
using namespace std;
int n;
long long a[5010], dp[5010], br, stek[5010];
set<long long> st;
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%lld", &a[i]);
    st.insert(a[i]);
  }
  for (set<long long>::iterator it = st.begin(); it != st.end(); it++)
    stek[++br] = *it;
  for (int i = 1; i <= n; i++) {
    long long pom = 1e18;
    for (int j = 1; j <= br; j++) {
      pom = min(pom, dp[j]);
      dp[j] = pom + abs(stek[j] - a[i]);
    }
  }
  long long rez = 1e18;
  for (int i = 1; i <= br; i++) rez = min(rez, dp[i]);
  printf("%lld\n", rez);
  return 0;
}
