1 #include<cstdio>
2 #include<cstring>
3 #include<algorithm>
4 #define mem(a) memset(a,127,sizeof(a))
5 const int N=2e3+10;
6 using std::min;
7 int read(){
8 int ans=0,f=1;char c=getchar();
9 while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
10 while(c>='0'&&c<='9'){ans=ans*10+c-48;c=getchar();}
11 return ans*f;
12 }
13 int abs(int x){return x>0?x:-x;}
14 int f[N][N],n,ans=2147483647,a[N],b[N];
15 void init(){
16 mem(f);
17 for(int i=0;i<=n+1;i++)f[0][i]=0;
18 }
19 /*-----------------------------------------------------*/
20 int main(){
21 n=read();
22 for(int i=1;i<=n;i++)b[i]=a[i]=read();
23 init();std::sort(b+1,b+1+n);
24 for(int i=1;i<=n;i++)
25 for(int j=1;j<=n;j++)
26 f[i][j]=min(f[i][j-1],f[i-1][j]+abs(b[j]-a[i]));
27 ans=min(ans,f[n][n]);init();
28 for(int i=1;i<=n;i++)
29 for(int j=n;j>=1;j--)
30 f[i][j]=min(f[i][j+1],f[i-1][j]+abs(b[j]-a[i]));
31 ans=min(ans,f[n][1]);
32 printf("%d",ans);
33 return 0;
34 }