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 math
from math import gcd
INF = float("inf")

import sys
input=sys.stdin.readline
sys.setrecursionlimit(500*500)
import itertools
from collections import Counter,deque

def main():
    n = int(input())
    a = list(map(int, input().split()))
    ans = 0
    k = a[0]
    for i in range(1,n):
        if a[i] < k:
            ans += k-a[i]
            a[i] = k
        k = a[i]
    print(ans)


if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
from itertools import accumulate


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

run_max = list(accumulate(a, max))


min_sum = sum([x - y for x, y in zip(run_max, a)])
print(min_sum)

Submission status: Accepted

Solution code:
# import sys
# import math #sqrt,gcd,pi
# import decimal
# import queue # queue
# import bisect
# import heapq # priolity-queue
# import time
# from itertools import product,permutations,\
    # combinations,combinations_with_replacement
# 重複あり順列、順列、組み合わせ、重複あり組み合わせ
# import collections # deque
# from operator import itemgetter,mul
# from fractions import Fraction
# from functools import reduce

mod = int(1e9+7)
# mod = 998244353
INF = 1<<50

def readInt():
    return list(map(int,input().split()))

def main():
    n = int(input())
    a = readInt()
    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]
    print(ans)
    return

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
import sys

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

ans = 0
tall = A[0]

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

print(ans)

Submission status: Accepted

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

a_max = [a[0]]
for i in range(1,n):
    a_max.append(max(a_max[i-1],a[i]))
print(sum(a_max)-sum(a))

Submission status: Accepted

Solution code:
import bisect, collections, copy, heapq, itertools, math, string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int, sys.stdin.readline().rstrip().split())
def LI(): return list(map(int, sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())

N = I()
A = LI()

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

Submission status: Accepted

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

fumi = 0
maxA = A[0]
for x in A:
    if x < maxA:
        fumi += maxA - x
    else:
        maxA = x
print(fumi)

Submission status: Accepted

Solution code:
import sys
import math
N = int(input())
A = [0]+list(map(int, input().split()))
ans = 0

for i in range(1, N+1):
    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()))
temp=A[0]
ans=0
for i in range(1,N):
  if temp>A[i]:
    ans+=temp-A[i]
  else:
    temp=A[i]
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
N = int(input())
A = list(map(int, input().split()))

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

Submission status: Accepted

Solution code:
n=int(input())
input_list = list(map(int,input().split()))
count = 0
temp = input_list[0]
for num in input_list:
    if num>temp:
        temp = num
    else:
        count += temp-num
print(count)

Submission status: Accepted

Solution code:
import sys, io, os, re
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from pprint import pprint
from math import sin, cos, pi, radians, sqrt, floor, ceil
from copy import copy, deepcopy
from collections import deque
from fractions import gcd
from functools import reduce
from itertools import groupby
from heapq import heapify, heappush, heappop

# sys.setrecursionlimit(5000)

n1 = lambda: int(sys.stdin.readline().strip())
nn = lambda: list(map(int, sys.stdin.readline().strip().split()))
f1 = lambda: float(sys.stdin.readline().strip())
fn = lambda: list(map(float, sys.stdin.readline().strip().split()))
s1 = lambda: sys.stdin.readline().strip()
sn = lambda: list(sys.stdin.readline().strip().split())
nl = lambda n: [n1() for _ in range(n)]
fl = lambda n: [f1() for _ in range(n)]
sl = lambda n: [s1() for _ in range(n)]
nm = lambda n: [nn() for _ in range(n)]
fm = lambda n: [fn() for _ in range(n)]
sm = lambda n: [sn() for _ in range(n)]

def array1(n, d=0): return [d] * n
def array2(n, m, d=0): return [[d] * m for x in range(n)]
def array3(n, m, l, d=0): return [[[d] * l for y in xrange(m)] for x in xrange(n)]
def linc(A, d=1): return map(lambda x: x + d, A)
def ldec(A, d=1): return map(lambda x: x - d, A)

N = n1()
A = nn()

t = A[0]
ans = 0

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

print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

lim = 0
ans = 0
for a in A:
  ans += max(0, lim - a)
  lim = max(lim, a)
  #print(lim, a, ans)
  
print(ans)

Submission status: Accepted

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

ans = 0
for i in range(1,n):
    diff = max(0, a[i-1] - a[i])
    ans += diff
    a[i] += diff

print(ans)

Submission status: Accepted

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

tmp = lis[0]
ans = 0

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

print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

a_prev = 0
ans = 0
for a in A:
    if a < a_prev:
        ans += a_prev - a
        a = a_prev
    a_prev = a

print(ans)

Submission status: Accepted

Solution code:
import sys
N = int(input())
A = [int(i) for i in input().split()]
cur = A[0]
if N == 1:
    print(0)
    sys.exit()
ans = 0
for a in A[1:]:
    if a < cur:
       ans += abs(cur-a)
    else:
        cur = a
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
min_size = A[0]
res = 0
for i in range(N):
  if A[i] < min_size:
    d = min_size - A[i]
    res += d
  elif A[i] > min_size:
    min_size = A[i]
print(res)

Submission status: Accepted

Solution code:
#N,X,T=map(int,input().split())
N=int(input())
A=list(map(int,input().split()))
h=A[0]
ans=0

for i in range(1,N):
    if h>A[i]:
        ans+=(h-A[i])
    elif h<A[i]:
        h=A[i]

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import math
from decimal import *
import random

def pf(n):
    ans = [1]
    if(n%2==0):
        if(n!= 2):
            ans.append(2)
        while(n%2==0):
            n//=2
    p = 3
    while(n>1):
        if(n%p==0):
            ans.append(p)
            while(n%p==0):
                n//=p
        p+=1
    return ans

n =int(input())
ans = 0
arr = list(map(int, input().split()))
mx = arr[0]
for i in range(1, n):
    if(arr[i]< mx):
        ans+=(mx-arr[i])
    else:
        mx = max(mx, arr[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, radians, atan2, degrees
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy,copy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd

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()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7


def main():
    N = INT()
    A = LIST()

    ans = [0]*N
    p = 0

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

    print(sum(ans))

if  __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate, product, combinations_with_replacement
import sys
import bisect
import string
import math
import time


def I(): return int(input())
def S(): return input()
def MI(): return map(int, input().split())
def MS(): return map(str, input().split())
def LI(): return [int(i) for i in input().split()]
def LI_(): return [int(i)-1 for i in input().split()]
def StoI(): return [ord(i)-97 for i in input()]
def ItoS(nn): return chr(nn+97)
def input(): return sys.stdin.readline().rstrip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def print_matrix(mat):
    for i in range(len(mat)):
        print(*['IINF' if v == IINF else "{:0=4}".format(v) for v in mat[i]])


yn = {False: 'No', True: 'Yes'}
YN = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**19
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
show_flg = False
# show_flg = True


def main():
    N = I()
    A = LI()
    mx = A[0]
    ans = 0

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

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

print(c)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from collections import defaultdict,deque
import math
def main():
    n = int(input())
    A=[int(i) for i in input().split()]
    res = 0
    highest = A[0]
    for i in range(1,n):
        if A[i] < highest:
            res += A[i]-highest

        if A[i] > highest:
            highest = A[i]

    print(abs(res))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict, deque
from copy import deepcopy
    
input = sys.stdin.readline
def RD(): return input().rstrip()
def F(): return float(input().rstrip())
def I(): return int(input().rstrip())
def MI(): return map(int, input().split())
def MF(): return map(float,input().split())
def LI(): return tuple(map(int, input().split()))
def LF(): return list(map(float,input().split()))
def Init(H, W, num): return [[num for i in range(W)] for j in range(H)]
    
    
def main():
    N = I()
    T = LI()
    res = 0
    past = T[0]
    for i in range(1, N):
        now = T[i]
        if now < past:
            res += (past-now)
        else:
            past = now
    print(res)
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys


inint = lambda: int(sys.stdin.readline())
inintm = lambda: map(int, sys.stdin.readline().split())
inintl = lambda: list(inintm())
instrm = lambda: map(str, sys.stdin.readline().split())
instrl = lambda: list(instrm())

n = inint()
A = inintl()

prev = A[0]

ans = 0

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

print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

ans = 0

step = a[0]

for i in range(n):
    if step > a[i]:
        diff = step - a[i]
        ans += diff
    step = max(step, a[i])

print(ans)

Submission status: Accepted

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

for i, value in enumerate(A):
    if value > height:
        height = value
    else:
        ans += height - value
    # print(i, value, height, ans)
print(ans)

Submission status: Accepted

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

cnt=0
m=a[0]

for i in range(1,n):
  if a[i]<m:
    cnt+=(m-a[i])
  elif a[i]>m:
    m=a[i]

print(cnt)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def LI(): return list(map(int, input().split()))
def I(): return map(int, input().split())
mod = 10**9 + 7

def main():
  n = int(input())
  a = LI()
  cnt = 0
  for i in range(1,n):
    if a[i-1] > a[i]:
      cnt += (a[i-1] - a[i])
      a[i] = a[i-1]
  print(cnt)
  
if __name__ == '__main__':
  main()

Submission status: Accepted

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

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

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

Submission status: Accepted

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

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#import sys
#import numpy as np
import math
#from fractions import Fraction
import itertools
from collections import deque
from collections import Counter
import heapq
from fractions  import gcd
#input=sys.stdin.readline
#import bisect
n=int(input())
a=list(map(int,input().split()))
r=a[0]
ans=0
for i in range(1,n):
    if a[i]<r:
        ans+=(r-a[i])
    else:
        r=a[i]
print(ans)

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
for i in range(1, len(a)):
    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()))
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()))
ans = 0
for i in range(n-1):
    if(a[i]>a[i+1]):
        ans += a[i]-a[i+1]
        a[i+1]=a[i]
print(ans)

Submission status: Accepted

Solution code:
from sys import exit
import math
ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))

n = input()
a = li()

cnt=0
for i in range(len(a)-1):
    if a[i] > a[i+1]:
        cnt += a[i]-a[i+1]
        a[i+1] += (a[i]-a[i+1])

print(cnt)

Submission status: Accepted

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

step = 0
before_max = A[0]

for i in range(1, N):
    if (A[i] >= before_max):
        before_max = A[i]
    else:
        step += before_max - A[i]

print(step)

Submission status: Accepted

Solution code:
N=int(input())
d=input().split()
D=[int(s) for s in d]
ans=0
for i in range(1,N):
    if D[i-1]>D[i]:
        x=D[i-1]-D[i]
        ans+=x
        D[i]=D[i-1]
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
l=[*map(int,input().split())]
t=l[0]
a=0
for i in l:
  if i>t: t=i
  a+=t-i
print(a)

Submission status: Accepted

Solution code:
import sys, re
from math import ceil, floor, sqrt, pi, factorial, gcd
from copy import deepcopy
from collections import Counter, deque
from heapq import heapify, heappop, heappush
from itertools import accumulate, product, combinations, combinations_with_replacement
from bisect import bisect, bisect_left, bisect_right
from functools import reduce
from decimal import Decimal, getcontext
# input = sys.stdin.readline 
def i_input(): return int(input())
def i_map(): return map(int, input().split())
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return input()
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_str(N): return [s_list() for _ in range(N)]
def s_row_list(N): return [list(s_input()) for _ in range(N)]
def lcm(a, b): return a * b // gcd(a, b)
sys.setrecursionlimit(10 ** 6)
INF = float('inf')
MOD = 10 ** 9 + 7
num_list = []
str_list = []

def main():
    n = i_input()
    num_list = i_list()

    count = 0

    max_num = num_list[0]

    for i in range(1,n):
        if num_list[i] < max_num:
            count += max_num - num_list[i]
        else:
            max_num = num_list[i]

    print(count)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    sys.setrecursionlimit(10**7)
    INF = 10**18
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    _LI = lambda : [int(x)-1 for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())
    SI = lambda : sys.stdin.readline().rstrip()

    N = NI()
    A = LI()
    t = A[0]
    ans = 0
    for x in A[1:]:
        if x < t:
            ans += t - x
        else:
            t = x
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def resolve():
    n = int(input())
    a = list(map(int, input().split()))
    ans = 0
    mini = a[0]

    for i in range(1, n):
        if a[i] >= mini:
            mini = a[i]
        else:
            ans += mini-a[i]
    print(ans)
resolve()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
 
## Library
 
import sys
from fractions import gcd
import math
from math import ceil,floor
import collections
from collections import Counter
import itertools
import copy

## input
 
# N=int(input())
# A,B,C,D=map(int, input().split())
# S = input()
# yoko = list(map(int, input().split()))
# tate = [int(input()) for _ in range(N)]
# N, M = map(int,input().split()) 
#    P = [list(map(int,input().split())) for i in range(M)]
#    S = []
#    for _ in range(N):
#        S.append(list(input()))

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]
    if tmp < A[i]:
        tmp = A[i]
    
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
li = list(map(int,input().split()))
humi = li[0]
ans = 0
for l in li[1:]:
    if l <= humi:
        ans += humi - l
    else:
        humi = l
print(ans)

Submission status: Accepted

Solution code:
def main():
    number_of_person = int(input())
    array = [int(x) for x in input().split()]
    pre_h = 0
    step_total = 0
    for height in array:
        step_total += max(pre_h - height, 0)
        pre_h = max(height, pre_h)
    return step_total


if __name__ == '__main__':
    ans = main()
    print(ans)

Submission status: Accepted

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

maxb = a[0]
ans = 0
for i in a:
    if(maxb < i):
        maxb = i
    else:
        ans += maxb-i
    #print(maxb)
print(ans)

Submission status: Accepted

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

count = 0

for i in range(N - 1):
    if A[i + 1] < A[i]:
        count += A[i] - A[i + 1]
        A[i + 1] = A[i]

print(count)

Submission status: Accepted

Solution code:
"""
    Satwik_Tiwari ;) .
    21st AUGUST , 2020  - FRIDAY
"""

#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function

from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase

from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned

#==============================================================================================
#fast I/O region
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")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
  def wrapped_func(*args, **kwargs):
    if stack: return f(*args, **kwargs)
    to = f(*args, **kwargs)
    while True:
      if type(to) is GeneratorType:
        stack.append(to)
        to = next(to)
        continue
      stack.pop()
      if not stack: break
      to = stack[-1].send(to)
    return to
  return wrapped_func
#### END ITERATE RECURSION ####

#===============================================================================================
#some shortcuts

mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n")  #as stdout.write always print sring.
def testcase(t):
    for p in range(t):
        solve()
def printlist(a) :
    for p in range(0,len(a)):
        out(str(a[p]) + ' ')
def google(p):
    print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
    res = 1     # Initialize result
    x = x % p  # Update x if it is more , than or equal to p
    if (x == 0) :
        return 0
    while (y > 0) :
        if ((y & 1) == 1) : # If y is odd, multiply, x with result
            res = (res * x) % p

        y = y >> 1      # y = y/2
        x = (x * x) % p
    return res
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) :
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

#===============================================================================================
# code here ;))
@iterative
def dfs(v,visited,st,new):
    new.append(st)
    visited[st] = 1
    for i in v[st]:
        if(visited[i] == 0):
            ok = yield dfs(v,visited,i,new)
    yield True


def solve():
    n = int(inp())
    a = lis()
    ans = 0
    for i in range(1,n):
        if(a[i] >= a[i-1]):
            continue
        else:
            ans+=a[i-1]-a[i]
            a[i] = a[i-1]

    print(ans)






testcase(1)
# testcase(int(inp()))

Submission status: Accepted

Solution code:
N = input()
A = map(int, input().split())
current = 0
ans = 0
for a in A:
  ans += current - min(current, a)
  current = max(current, a)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
A = [int(_) for _ in input().split()]
ans = 0
before = A[0]
for a in A[1:]:
    if before > a:
        ans += before - a
        a = before
    before = a
print(ans)

Submission status: Accepted

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

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

Submission status: Accepted

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

cnt = 0
prv = 0

for i in range(N):
    now = A[i]
    if prv > now:
        cnt += prv - now
    else:
        prv = now

print(cnt)

Submission status: Accepted

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

Submission status: Accepted

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

h=0
ans=0

for i in range(N):
	a=A_ls[i]
	h=max(h,a)
	ans+=h-a

print(ans)
# 2darray [[0] * 4 for i in range(3)]
# import itertools

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
ans = 0
m = 0
for i in range(N):
  if m >= A[i]:
    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
for i in range(N-1):
    if A[i] > A[i+1]:
        ans += A[i] - A[i+1]
        A[i+1] = A[i]

print(ans)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
if n==1:
    print(0)
else:
    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]
    print(ans)

Submission status: Accepted

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

max_h,ans = A[0],0
for i in range(1,N):
    if max_h > A[i]:
        ans += (max_h - A[i])
    else:
        max_h = 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):
  s=a[i-1]
  t=a[i]
  if t<s:
    a[i]+=s-t
    ans+=s-t
    
print(ans)