N = int(input()) H = list(map(int, input().split())) X = [10 **9 + 1] xlen = 1 tmp = 0 for i in range(N): h = H[i] while X[-1] <= h: tmp -= X.pop() * (-1) ** (xlen) xlen -= 1 if xlen % 2 == (i + 1) % 2: X.append(h) xlen += 1 tmp += h * (-1) ** (i) print(tmp)