Program Zeroing;
Type
        s=record
                z:longint;
                n:integer;
                p:integer;
        end;
Var
        M:array[1..200000] of s;
        a,n,i:longint;
        t:int64;
        f,fl:boolean;
Begin
        Read(N);
        Read(M[1].z);
        M[1].p:=-1;
        a:=1;
        for i:=2 to N do
        begin
                Read(M[i].z);
                if M[i].z<>M[a].z then begin
                        M[a].n:=i;
                        M[i].p:=a;
                        a:=i;
                end;
        end;
        if a<>n then M[N].p:=a;
        M[N].n:=-1;
        t:=0;
        while (M[1].p<>-1)or(M[1].n<>-1) do
        begin
                i:=1;
                fl:=true;
                while (fl)and(i<>-1) do
                begin
                        f:=true;
                        if M[i].p<>-1 then begin
                                if M[M[i].p].z>M[i].z then f:=false;
                        end;
                        if ((f)and(M[i].n<>-1)) then begin
                                if M[M[i].n].z>M[i].z then f:=false;
                        end;
                        if f then begin
                                if M[i].p=-1 then begin
                                        a:=M[i].n;
                                        t:=t+M[i].z-M[a].z;
                                        M[i].z:=M[a].z;
                                        M[i].n:=M[a].n;
                                        if M[a].n<>-1 then M[M[a].n].p:=i;
                                end
                                else if M[i].n=-1 then begin
                                        a:=M[i].p;
                                        t:=t+M[i].z-M[a].z;
                                        M[a].n:=M[i].n;
                                        if M[i].n<>-1 then M[M[i].n].p:=a;
                                end
                                else if M[M[i].n].z>M[M[i].p].z then begin
                                        a:=M[i].n;
                                        t:=t+M[i].z-M[a].z;
                                        M[i].z:=M[a].z;
                                        M[i].n:=M[a].n;
                                        if M[a].n<>-1 then M[M[a].n].p:=i;
                                end
                                else begin
                                        a:=M[i].p;
                                        t:=t+M[i].z-M[a].z;
                                        M[a].n:=M[i].n;
                                        if M[i].n<>-1 then M[M[i].n].p:=a;
                                end;
                        end;
                        if i<>-1 then begin
                                i:=M[i].n;
                        end
                        else fl:=false;
                end;
        end;
        t:=t+M[1].z;
        Write(t);
End.

