N=int(input()) H=list(map(int,input().split())) S=[10**10] now=0 for i in range(N): hi=H[i] while S[-1]<=hi: c=S.pop() if len(S)%2==0: now+=c else: now-=c if (len(S)-i)%2==1: S.append(hi) if i%2==0: now+=hi else: now-=hi print(now)