from collections import deque N=int(input()) A=deque(map(int, input().split())) res=0 for i in range(N): a=A[0]-A[1] b=A[-1]-A[-2] if a>b: A.popleft() A.popleft() res+=a else: A.pop() A.pop() res+=b print(res)