N = int(input()) H = list(map(int, input().split())) ans = 0 stack = [(10 ** 18, -1)] for i, h in enumerate(H): now = 2 * (1 - i % 2) - 1 while stack[-1][0] <= h: a, b = stack.pop() ans -= a * b if now != stack[-1][1]: stack.append((h, now)) ans += h * now print(ans)