N = int(input()) A = [0] + list(map(int, input().split())) + [10**18] ans = 0 for i in range(1, N + 1): if A[i] <= A[i + 1]: continue # 左をできるだけ下げる d = A[i] - max(A[i - 1], A[i + 1]) ans += d A[i] -= d if A[i] <= A[i + 1]: continue # 右を上げる d = A[i] - A[i + 1] ans += d A[i+1] += d print(ans)