n=int(input()) h=list(map(int,input().split())) stack=[1<<60] now=0 for i in range(n): hi=h[i] while stack[-1]<=hi: c=stack.pop() if len(stack)%2==0: now+=c else: now-=c if (len(stack)-i)%2==1: stack.append(hi) if i%2: now-=hi else: now+=hi print(now)