N = int(input())
array = list(map(int,input().split()))

def func(c,result):
    num = max(array[0:c])
    idx = array.index(num)
    result += (-sum(array[idx:c]) + (num*(c-idx)))
    if idx == 0:
        print(result)
        return
    func(idx,result)
    
res = func(N,0)