n = int(input()) h = list(map(int, input().split())) q = [] ans = 0 for i in range(n): while q and q[-1][0] <= h[i]: r, l = q.pop() ans -= r - l if i%2: if q: ans -= max(0, h[i] - q[-1][1]) q[-1][1] = max(h[i], q[-1][1]) else: if q: q.append([min(q[-1][1], h[i]), 0]) else: q.append([h[i], 0]) ans += q[-1][0] - q[-1][1] print(ans)