#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<set>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
#include<iostream>
#include<string>
#include<cmath>
#define FOR(i,a,b) for(i=(a);i<=(b);i++)
#define ROF(i,a,b) for(i=(a);i>=(b);i--)
#define INF 2147000000
#define N 2010
typedef long long LL;
using namespace std;
int a[N],f[N][N],b[N];
int main()
{
int n,i,j;
scanf("%d",&n);
FOR(i,1,n) {scanf("%d",&a[i]);b[i]=a[i];}
sort(b+1,b+1+n);
FOR(i,0,n) f[i][0]=INF;
FOR(i,1,n) FOR(j,1,n) f[i][j]=min(f[i][j-1],f[i-1][j]+abs(a[i]-b[j]));
int a1=f[n][n];
FOR(i,0,n) f[i][n+1]=INF;
FOR(i,1,n) ROF(j,n,1) f[i][j]=min(f[i][j+1],f[i-1][j]+abs(a[i]-b[j]));
int a2=f[n][1];
printf("%d\n",min(a1,a2));
}