program xmz;
var
f1,f2:text;
x:array[0..2000]of int64;
f:array[0..2000]of int64;
c:array[0..2000]of int64;
t,min:int64;
a,b,n,d:longint;
begin
assign(f1,'roady.in');assign(f2,'roady.out');
reset(f1);rewrite(f2);
read(f1,n);
for a:=1 to n do
begin
read(f1,x[a]);
c[a]:=x[a];
end;
for a:=1 to n do
for b:=a+1 to n do
if c[a]>c[b] then begin t:=c[a];c[a]:=c[b];c[b]:=t;end;
for a:=1 to n do
for b:=1 to n do
begin
if x[a]>c[b] then f[b]:=f[b]+x[a]-c[b] else
if x[a]<x[a-1] then f[b]:=f[b]+x[a-1]-x[a];
end;
min:=999999999999;
for b:=1 to n do
if f[b]<min then min:=f[b];
fillchar(f,sizeof(f),0);
x[0]:=99999999999;
for a:=1 to n do
for b:=1 to n do
begin
if x[a]<c[b] then
f[b]:=f[b]+c[b]-x[a] else
if x[a]>x[a-1] then f[b]:=f[b]+x[a]-x[a-1];
end;
for b:=1 to n do
if f[b]<min then min:=f[b];
write(f2,min);
close(f1);close(f2);
end.