Problem:


Score : 300 points

Problem Statement

N persons are standing in a row. The height of the i-th person from the front is A_i.

We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:

Condition: Nobody in front of the person is taller than the person. Here, the height of a person includes the stool.

Find the minimum total height of the stools needed to meet this goal.

Constraints

1 \leq N \leq 2\times 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print the minimum total height of the stools needed to meet the goal.

Sample Input 1

5
2 1 5 4 3

Sample Output 1

4

If the persons stand on stools of heights 0, 1, 0, 1, and 2, respectively, their heights will be 2, 2, 5, 5, and 5, satisfying the condition.

We cannot meet the goal with a smaller total height of the stools.

Sample Input 2

5
3 3 3 3 3

Sample Output 2

0

Giving a stool of height 0 to everyone will work.



Sample input:
5
2 1 5 4 3


Sample output:
4

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict, Counter, namedtuple, deque
import itertools
import functools
import bisect
import heapq
import math
import copy
# from fractions import gcd

MOD = 10 ** 9 + 7
# MOD = 998244353
# sys.setrecursionlimit(10**8)

n = int(input())
A = list(map(int, input().split()))
s = 0
for i in range(1, n):
    if A[i-1] > A[i]:
        s += A[i - 1] - A[i]
        A[i] += A[i-1] - A[i]

print(s)

Submission status: Accepted

Solution code:
# for #!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase


# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion
class union_find:
    def __init__(self, n):
        self.n = n
        self.rank = [0]*n
        self.parent = [int(j) for j in range(n)]
    
    def union(self,i,j):
        i = self.find(i)
        j = self.find(j)
        if self.rank[i] == self.rank[j]:
            self.parent[i] = j
            self.rank[j] += 1

        elif self.rank[i] > self.rank[j]:
            self.parent[j] = i
        else:
            self.parent[i] = j

    def find(self, i):
        temp = i
        if self.parent[temp] != temp:
            self.parent[temp] = self.find(self.parent[temp])
        return self.parent[temp]
from math import log2, ceil
from collections import deque, Counter as CC
def main():
# Enter your code here. Read input from STDIN. Print output to STDOUT
    # for t in range(int(input())):
        
        n = int(input())
        # n,x,t = [int(j) for j in input().split()]
# )
        l = [int(j) for j in input().split()]
        tmp = l[0]
        ans = 0
        for i in range(1,n):
            if(l[i]<tmp):
                ans+=tmp-l[i]
            else:
                tmp = l[i]
        print(ans)



        # b = [int(j) for j in input().split()]

            # s = n-1

        # s = input()




        # a = list(a)
        # print(a)
        # for i in a:



        



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n=int(input())
arr=list(map(int,raw_input().split()))

def solve(arr,n):
    if arr==sorted(arr):
        return 0
    ans=0
    m=arr[0]
    for i in range(1,n):
        if arr[i]<m:
            ans+=m-arr[i]
        else:
            m=arr[i]
    return ans
print(solve(arr,n))

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))

ans = 0
h = 0
for i in range(n):
  if a[i] < h:
    ans += h - a[i]
  else:
    h = a[i]
print(ans)

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10 ** 8)
from itertools import accumulate
from itertools import permutations
from itertools import combinations
from collections import defaultdict
from collections import Counter
import fractions
import math
from collections import deque
from bisect import bisect_left
from bisect import bisect_right
from bisect import insort_left
import itertools
from heapq import heapify
from heapq import heappop
from heapq import heappush
import heapq
from copy import deepcopy
from decimal import Decimal
alf = list("abcdefghijklmnopqrstuvwxyz")
ALF = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
#import numpy as np
INF = float("inf")
#d = defaultdict(int)
#d = defaultdict(list)
N = int(input())
A = list(map(int,input().split()))
ans = 0
m = 0
for i in range(N):
    a = A[i]
    if m < a:
        m = a
    else:
        ans += (m-a)
print(ans)

Submission status: Accepted

Solution code:
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
#from bisect import bisect_left as bl, bisect_right as br, insort
#from heapq import heapify, heappush, heappop
#from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
from decimal import Decimal
#from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7

n=int(data())
h=mdata()
m=0
ans=0
for i in h:
    m = max(m, i)
    ans+=m-i
out(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))
ans = 0
maxA = 0
for i in A:
    if i < maxA: ans += maxA - i
    else: maxA = i
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
s = 0
ans = 0

for i in range(n):
    if s > a[i]:
        ans += s - a[i]
    else:
        s = a[i]
print(ans)

Submission status: Accepted

Solution code:
import sys


def main():
    input = sys.stdin.buffer.readline
    n = int(input())
    a = list(map(int, input().split()))
    ans = 0
    forward = 0
    for i in range(n):
        if a[i] < forward:
            ans += forward - a[i]
        else:
            forward = a[i]
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**9)

def mi(): return map(int,input().split())
def ii(): return int(input())
def isp(): return input().split()
def deb(text): print("-------\n{}\n-------".format(text))

INF=10**20
def main():
    N=ii()
    A=list(mi())

    mx = 0
    ans = 0
    for i in range(N):
        if mx > A[i]:
            ans += mx - A[i]
            A[i] = mx
        
        mx = max(mx,A[i])

    print(ans)

        
        






if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))

tmp = A[0]
ans = 0
for i in range(1, N):
  if A[i] > tmp:
    tmp = A[i]
  else:
    ans += tmp-A[i]
print(ans)

Submission status: Accepted

Solution code:
(N,) = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
ans = 0
mn = A[0]
for i in range(N):
    ans += max(0, mn - A[i])
    mn = max(mn, A[i])
print(ans)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce, lru_cache
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 
#mod = 998244353
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

N = INT()
A = LIST()

ans = 0
tmp = A[0]

for a in A[1:]:
	ans += max(0, tmp-a)
	tmp = max(tmp, a)

print(ans)

Submission status: Accepted

Solution code:
def solve():
    N = int(input())
    A = list(map(int,input().split()))

    cnt = 0
    mx = A[0]
    for i in range(1,N):
        if A[i] > mx:
            mx = A[i]
        else:
            cnt += mx - A[i]
    
    print(cnt)

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
n = int(input())
a = [int(x) for x in input().split()]

mx = a[0]

ans = 0

for x in a:
    if x < mx:
        ans += (mx - x)
    else:
        mx = x 
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))

ans = 0
mx = A[0]
for i in range(1, N):
    if A[i] < mx:
        ans += mx - A[i]
    mx = max(mx, A[i])
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))

s = 0
for i in range(1,n):
    if a[i-1] > a[i]:
        s += a[i-1] - a[i]
        a[i] = a[i-1]

print(s)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.buffer.readline
N = int(input())
A = list(map(int, input().split()))

v = A[0]
ans = 0
for a in A:
    if v > a:
        ans += v - a
    if v < a:
        v = a
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))

ans = 0

for i in range(1, N):
  ans += max(A[i-1] - A[i], 0)
  A[i] = max(A[i-1], A[i])

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))

max_a = A[0]
ans = 0
for i in range(1, N):
    if(A[i] < max_a):
        ans += max_a-A[i]
    else:
        max_a = A[i]
        
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = [int(a) for a in input().split(" ")]

ans = 0
for i in range(len(A)):
  if i == 0:
    continue
  else:
    if A[i] < A[i - 1]:
      ans += A[i - 1] - A[i]
      A[i] = A[i - 1]

print(ans)

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
num=0
ans=0
for i in range(N):
    if A[i]>num:
        num=A[i]
    ans+=num-A[i]
print(ans)

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    A = list(map(int, input().split()))
    ans, m = 0, 0
    for a in A:
        if a < m:
            ans += m - a
        else:
            m = a
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split())) + [0]
ans = 0
maxh = a[0] 
for i in range(n):
    if maxh > a[i]:
        ans += maxh - a[i]
        a[i] = maxh
    else:
        maxh = a[i]
print(ans)

Submission status: Accepted

Solution code:
N, *A = map(int, open(0).read().split())

result = 0
p = A[0]
for i in range(1, N):
    if p >= A[i]:
        result += p - A[i]
    else:
        p = A[i]
print(result)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))

ans = 0
mae = A[0]
for i in range(1, N):
    if mae > A[i]:
        ans += mae - A[i]
    else:
        mae = A[i]

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
A = list(map(int,input().split()))
big = A[0]
cnt = 0
for i in range (1,n):
    if A[i] < big:
        cnt += big-A[i]
    else:
        big = A[i]
print(cnt)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
r=0
for i in range (1,n):
    if a[i]<a[i-1]:
        r+=a[i-1]-a[i]
        a[i]=a[i-1]
print(r)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
ans = 0
num = a[0]
for i in range(n - 1):
    ans += max(num - a[i + 1], 0)
    num = max(num, a[i + 1])
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
t=0
for i in range(n-1):
    x,y=a[i],a[i+1]
    if x>=y:
        a[i+1]=x
        t+=x-y
print(t)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))

mx = a[0]
ans = 0
for i in range(1, n):
    if a[i] < mx:
        ans += mx - a[i]
    mx = max(mx, a[i])
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
l=list(map(int,input().split()))
mx=l[0]
an=0
for i in range(1,n):
  if l[i]<mx:
    an+=mx-l[i]
  else:
    mx=l[i]
print(an)

Submission status: Accepted

Solution code:
import sys, bisect, math, itertools, heapq, collections
from operator import itemgetter
# a.sort(key=itemgetter(i)) # i番目要素でsort
from functools import lru_cache
# @lru_cache(maxsize=None)
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
INF = float('inf')
mod = 10**9 + 7
eps = 10**-7


def inp():
    '''
    一つの整数
    '''
    return int(input())


def inpl():
    '''
    一行に複数の整数
    '''
    return list(map(int, input().split()))


def str_inp():
    '''
    文字列をリストとして読み込む
    '''
    return list(input()[:-1])


n = inp()
a = inpl()
now = 0
ans = 0
for i in range(n):
    if now > a[i]:
        ans += now - a[i]
    else:
        now = a[i]
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
A=list(map(int,input().split()))

num,height=0,A[0]
B=[]
for i in range(1,n):
    if height>A[i]:
        B.append(height-A[i])
        num=max(num,height-A[i])
    else:height=A[i]
print(sum(B))

Submission status: Accepted

Solution code:
import math
from collections import defaultdict
ml=lambda:map(int,input().split())
ll=lambda:list(map(int,input().split()))
ii=lambda:int(input())
ip=lambda:input()

"""========main code==============="""
t=1
#t=ii()
for _ in range(t):
    n=ii()
    a=ll()
    ans=0
    for i in range(1,n):
        if(a[i]<a[i-1]):
            ans+=(a[i-1]-a[i])
            a[i]=a[i-1]
    print(ans)

Submission status: Accepted

Solution code:
def resolve():
    N = int(input())
    A = list(map(int, input().split()))
    hmax = A[0]
    total = 0
    for i in range(1, N):
        if hmax > A[i]:
            total += hmax-A[i]
        else:
            hmax = A[i]
    print(total)


if '__main__' == __name__:
    resolve()

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
ans=0
for i in range(1,n):
  if a[i-1]>a[i]:
    ans=ans+a[i-1]-a[i]
    a[i]=a[i-1]
print(ans)

Submission status: Accepted

Solution code:
## coding: UTF-8

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


ans = 0
now_max = A[0]

for i in range(1, N):
    #print(A[i])
    if(now_max < A[i]):
        now_max = A[i]
    else:
        ans += now_max - A[i]

print(ans)

Submission status: Accepted

Solution code:
import sys, math
from collections import defaultdict, deque, Counter
from bisect import bisect_left, bisect_right
from itertools import combinations, permutations, product
from heapq import heappush, heappop
from functools import lru_cache
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 1000000007
sys.setrecursionlimit(1000000)

N = ri()
A = rl()

s = 0
prev = A[0]
for i in range(1, N):
	if A[i] < prev:
		dif = prev-A[i]
		A[i] += dif
		s += dif
	prev = A[i]
print(s)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
ans = 0
for i in range(1, n):
    ans += max(a[i-1] - a[i], 0)
    a[i] = max(a[i-1], a[i])
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
ans = 0
high = a[0]
for i in range(1, n):
    if a[i] < high:
        ans += high - a[i]
    else:
        high = a[i]
print(ans)

Submission status: Accepted

Solution code:
INT = lambda: int(input())
INTM = lambda: map(int,input().split())
STRM = lambda: map(str,input().split())
STR = lambda: str(input())
LIST = lambda: list(map(int,input().split()))
LISTS = lambda: list(map(str,input().split()))
def do():
    n=INT()
    A=LIST()
    ans=0
    mina=0
    for a in A:
        mina=max(mina,a)
        ans+=max(0,mina-a)
    
    print(ans)
    
if __name__ == '__main__':
    do()

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))

step = 0
for i in range(1, n):
    if a[i-1] > a[i]:
        step += a[i-1]-a[i]
        a[i] = a[i-1]
print(step)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))

ans = 0
m = a[0]
for i in range(n):
    if a[i] < m:
        ans += m-a[i]
    else:
        m = a[i]
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
ans = 0
cur = a[0]
for i in range(1, n):
    if cur <= a[i]:
        cur = a[i]
    else:
        ans += cur - a[i]
        a[i] = cur
        cur = a[i]
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))

ans=0
for i in range(1,n):
    if a[i-1]<=a[i]:
        continue
    x=a[i-1]-a[i]
    ans+=x
    a[i]+=x
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
li = list(map(int, input().split()))

check = 0
ans = 0
for i in range(n):
    if i == 0:
        check = li[0]
        continue
    
    if check >= li[i]:
        ans += check - li[i]
    else:
        check = li[i]
        
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int, input().split()))

ans=0
for i in range(1,n):
    if a[i]<a[i-1]:
        ans+=a[i-1]-a[i]
        a[i]=a[i-1]
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))

prev = 0
ans = 0
for a in A:
  if a >= prev:
    prev = a
  else:
    ans += prev-a


print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
cnt = 0
before = a[0]

for i in range(n):
    if before > a[i]:
        cnt += before - a[i]
    else:
        before = a[i]

print(cnt)

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    inlis = list(map(int, input().split()))

    tmp = inlis[0]
    ans = 0

    for i in range(1, n):
        if inlis[i] < tmp:
            ans += tmp - inlis[i]
        else:
            tmp = inlis[i]
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:

import sys
input = sys.stdin.readline
N = int(input())
A = list(map(int,input().split()))

ans = 0
h = 0
for a in A:
	if h > a:
		ans += h - a
	else:
		h = a
print(ans)

Submission status: Accepted

Solution code:
#!python3

import sys
iim = lambda: map(int, sys.stdin.readline().rstrip().split())

def resolve():
    it = map(int, sys.stdin.read().split())
    N = next(it)
    A = list(it)

    ans = 0
    x = A[0]

    for i in range(1, N):
        ai = A[i]
        diff = x - ai
        if diff >= 0:
            ans += diff
        else:
            x = ai

    print(ans)

if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
from sys import stdin, setrecursionlimit
#input = stdin.buffer.readline
setrecursionlimit(10 ** 7)

from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
from collections import deque, defaultdict, Counter
from itertools import combinations, permutations, combinations_with_replacement
from itertools import accumulate
from math import ceil, sqrt, pi, radians, sin, cos

MOD = 10 ** 9 + 7
INF = 10 ** 18

N = int(input())
#N, M = map(int, input().split())
A = list(map(int, input().split()))
#A = [int(input()) for _ in range(N)]
#ABC = [list(map(int, input().split())) for _ in range(N)]
#S = input()
#S = [input() for _ in range(N)]

if N == 1:
    print(0)
    exit()
    
answer = 0
max_a = A[0]

for a in A[1:]:
    max_a = max(max_a, a)
    answer += max_a - a

print(answer)

Submission status: Accepted

Solution code:
n = int(input())
A = list(map(int,input().split()))
if n ==1: print(0);exit()
cnt = 0
for i in range(1,n):
    if A[i]<A[i-1]:
        cnt += A[i-1]-A[i]
        A[i] = A[i-1]
        
print(cnt)

Submission status: Accepted

Solution code:
from sys import stdin


def main():
    _in = [_.rstrip() for _ in stdin.readlines()]
    N = int(_in[0])  # type:int
    A_arr = list(map(int, _in[1].split(' ')))  # type:list(int)
    # vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    cnt = A_arr[0]
    ans = 0
    for A in A_arr:
        if A < cnt:
            ans += (cnt - A)
        else:
            cnt = A
    # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
n = ni()
A = lma()
prev=0
ans=0
for a in A:
    if a<prev:
        ans+=(prev-a)
    prev=max(a,prev)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
count = 0
max_height = A[0]

for i in range(N):
    if A[i] > max_height:
        max_height = A[i]
    elif A[i] == max_height:
        continue
    else:
        count += max_height - A[i]

print(count)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
last = -1
ans = 0
for i in range(n):
  if a[i] >= last:
    last = a[i]
  else:
    ans += last - a[i]
  #print(last)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
tmp = A[0]
ans = 0
for i in range(1, N):
    if tmp > A[i]:
        ans += tmp - A[i]
    else:
        tmp = A[i]
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
import pprint

sys.setrecursionlimit(10 ** 6)

class Logger:
	def __init__(self, debug):
		self.debug = debug
	def print(self, *args):
		if self.debug:
			pprint.pprint(args)


def main():
	log = Logger(0)
	n = int(sys.stdin.readline())
	a = list(map(int, sys.stdin.readline().split()))
	ans = 0
	for i in range(1, n):
		if a[i-1] > a[i]:
			ans += a[i-1] - a[i]
			a[i] = a[i-1]
	log.print(a)
	print(ans)

main()