import sys
input = lambda: sys.stdin.readline().rstrip()

def main():
    n = int(input())
    a = list(map(int, input().split()))
    idx_start = 0
    sum_a = 0
    ans = 0
    len_a = len(a)
    for i in range(1, len_a):
        if a[idx_start] < a[i]:
            ans += ((i - 1) * a[idx_start]) - sum_a
            idx_start = i
            sum_a = 0
        else:
            sum_a += a[i]
            if i == len_a - 1:
                ans += ((i - idx_start) * a[idx_start]) - sum_a
    print(ans)
if __name__ == '__main__':
    main()
