Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.

Omkar currently has $n$ supports arranged in a line, the $i$-th of which has height $a_i$. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in height in order to support the waterslide. In $1$ operation, Omkar can do the following: take any contiguous subsegment of supports which is nondecreasing by heights and add $1$ to each of their heights. 

Help Omkar find the minimum number of operations he needs to perform to make his supports able to support his waterslide!

An array $b$ is a subsegment of an array $c$ if $b$ can be obtained from $c$ by deletion of several (possibly zero or all) elements from the beginning and several (possibly zero or all) elements from the end.

An array $b_1, b_2, \dots, b_n$ is called nondecreasing if $b_i\le b_{i+1}$ for every $i$ from $1$ to $n-1$.


-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \leq t \leq 100$). Description of the test cases follows.

The first line of each test case contains an integer $n$ ($1 \leq n \leq 2 \cdot 10^5$) — the number of supports Omkar has.

The second line of each test case contains $n$ integers $a_{1},a_{2},...,a_{n}$ $(0 \leq a_{i} \leq 10^9)$ — the heights of the supports.

It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.


-----Output-----

For each test case, output a single integer — the minimum number of operations Omkar needs to perform to make his supports able to support his waterslide.


-----Example-----
Input
3
4
5 3 2 5
5
1 2 3 5 3
3
1 1 1

Output
3
2
0



-----Note-----

The subarray with which Omkar performs the operation is bolded.

In the first test case:

First operation:

$[5, 3, \textbf{2}, 5] \to [5, 3, \textbf{3}, 5]$

Second operation:

$[5, \textbf{3}, \textbf{3}, 5] \to [5, \textbf{4}, \textbf{4}, 5]$

Third operation:

$[5, \textbf{4}, \textbf{4}, 5] \to [5, \textbf{5}, \textbf{5}, 5]$

In the third test case, the array is already nondecreasing, so Omkar does $0$ operations.

Source: codeforces | Difficulty: EASY
Tags: Implementation

Greedy algorithms


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


import sys
import math
from collections import defaultdict, Counter
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	for j in range(n - 1, 0, -1):
		if a[j - 1] > a[j]:
			ans += a[j - 1] - a[j]
	print(ans)


import sys, math
from collections import deque, defaultdict
import operator as op
from functools import reduce
sys.setrecursionlimit(10 ** 6)
I = sys.stdin.readline

def ii():
	return int(I().strip())

def li():
	return list(map(int, I().strip().split()))

def mi():
	return map(int, I().strip().split())

def ncr(n, r):
	r = min(r, n - r)
	numer = reduce(op.mul, range(n, n - r, -1), 1)
	denom = reduce(op.mul, range(1, r + 1), 1)
	return numer // denom

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def main():
	ans = ''
	for _ in range(ii()):
		n = ii()
		arr = li()
		cnt = 0
		i = 0
		while i < n - 1:
			if arr[i] > arr[i + 1]:
				cnt += arr[i] - arr[i + 1]
			i += 1
		ans += str(cnt) + '\n'
	print(ans)
main()


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


t = int(input())

def solve():
	n = int(input())
	l = list(map(int, input().split()))
	ans = 0
	for i in range(1, n):
		ans += max(0, l[i - 1] - l[i])
	print(ans)
for i in range(t):
	solve()


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	count = 0
	p = 0
	for i in l:
		if p > i:
			count += p - i
		p = i
	print(count)


for s in [*open(0)][2::2]:
	a = (*map(int, s.split()),)
	print(sum((max(0, x - y) for (x, y) in zip(a, a[1:]))))


t = int(input())
for _ in range(t):
	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]
	print(ans)


def solve(arr):
	ans = 0
	for i in range(len(arr) - 1):
		ans += max(0, arr[i] - arr[i + 1])
	print(ans)
t = int(input())
for i in range(t):
	input()
	solve(list(map(int, input().split())))


import sys
input = sys.stdin.readline

def solve():
	n = int(input())
	ls = list(map(int, input().split()))
	ans = 0
	for i in range(n - 1):
		ans += max(0, ls[i] - ls[i + 1])
	print(ans)
T = int(input())
for _ in range(T):
	solve()


from sys import stdin
inp = lambda : stdin.readline().strip()
t = int(inp())
for _ in range(t):
	n = int(inp())
	a = [int(x) for x in inp().split()]
	maximum = a[0]
	currMax = 0
	ans = 0
	for i in range(1, len(a)):
		if a[i] < a[i - 1]:
			currMax = max(currMax, maximum - a[i])
		else:
			ans += currMax
			currMax = 0
			maximum = a[i]
		maximum = max(maximum, a[i])
	ans += currMax
	print(ans)


T = int(input())
for _ in range(T):
	input()
	l = list(map(int, input().split()))
	ans = 0
	for i in range(1, len(l)):
		ans += max(l[i - 1] - l[i], 0)
	print(ans)


def fact(x):
	if x == 0:
		return 1
	else:
		return x * fact(x - 1)

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val, lb, ub):
	ans = 0
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = 1
			break
	return ans

def kadane(x):
	sum_so_far = 0
	current_sum = 0
	for i in x:
		current_sum += i
		if current_sum < 0:
			current_sum = 0
		else:
			sum_so_far = mpos(sum_so_far, current_sum)
	return sum_so_far

def pref(li):
	pref_sum = [0]
	for i in li:
		pref_sum.append(pref_sum[-1] + i)
	return pref_sum
from math import *
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	for i in range(n - 1):
		ans += max(a[i] - a[i + 1], 0)
	print(ans)


import sys

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def rinput():
	return map(int, sys.stdin.readline().strip().split())

def get_list():
	return list(map(int, sys.stdin.readline().strip().split()))
mod = int(1000000000.0) + 7
for _ in range(iinput()):
	n = iinput()
	a = get_list()
	i = n - 1
	ans = 0
	for i in range(n - 1, 0, -1):
		if a[i - 1] > a[i]:
			ans += a[i - 1] - a[i]
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	a = [int(v) for v in input().split()]
	p = 0
	for j in range(1, n):
		if a[j] < a[j - 1]:
			p = p + a[j - 1] - a[j]
	print(p)


for _ in range(int(input())):
	n = int(input())
	k = list(map(int, input().split()))
	l = []
	c = 0
	for i in range(len(k) - 1):
		if k[i] > k[i + 1]:
			c += k[i] - k[i + 1]
	print(c)


def water_gorka(a):
	counter = 0
	for i in range(len(a) - 2, -1, -1):
		if a[i] > a[i + 1]:
			counter += a[i] - a[i + 1]
	return counter
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	print(water_gorka(a))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	i = 0
	ans = 0
	while i < n:
		c = a[i]
		j = i + 1
		while j < n and a[j] <= a[j - 1]:
			j += 1
		ans += a[i] - min(a[i:j])
		i = j
	print(ans)


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


t = int(input(''))
arr = []
for i in range(t):
	int(input(''))
	arr.append(list(map(int, input().split())))
for i in arr:
	n = len(i)
	sign = 0
	for j in range(1, n):
		if i[j] < i[j - 1]:
			sign = 1
			break
	if sign == 0:
		print(0)
		continue
	diff = i.copy()
	diff[0] = 0
	for j in range(1, n):
		if i[j] < i[j - 1]:
			diff[j] = i[j - 1] - i[j]
		else:
			diff[j] = 0
	print(sum(diff))


import sys
from math import sqrt, gcd, ceil, log, floor
from bisect import bisect, bisect_left
from collections import defaultdict, Counter, deque
from heapq import heapify, heappush, heappop
input = sys.stdin.readline
read = lambda : list(map(int, input().strip().split()))
MOD = 10 ** 9 + 7

def f(arr):
	ans = 0
	for i in range(len(arr) - 1, 0, -1):
		ans += max(0, arr[i - 1] - arr[i])
	return ans

def main():
	ans_ = []
	for _ in range(int(input())):
		n = int(input())
		arr = read()
		maxi = 0
		i = 1
		ans = 0
		while i < n:
			if arr[i] < arr[i - 1]:
				maxi = (arr[i - 1], i - 1)
				while i < n and arr[i] < maxi[0]:
					i += 1
				ans += f(arr[maxi[1]:i])
			else:
				i += 1
		ans_.append(ans)
	print('\n'.join(map(str, ans_)))
main()


def waterslide(arr):
	ans = 0
	for i in range(0, len(arr) - 1):
		ans += max(arr[i] - arr[i + 1], 0)
	return ans
t = int(input())
for u in range(t):
	y = input()
	print(waterslide(list(map(int, input().strip().split()))))


import sys
import math

def II():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def MI():
	return map(int, sys.stdin.readline().split())

def SI():
	return sys.stdin.readline().strip()
t = II()
for q in range(t):
	n = II()
	a = LI()
	d = [0] * n
	for i in range(1, n):
		if a[i] < a[i - 1]:
			d[i] = a[i - 1] - a[i]
		else:
			d[i] = 0
	print(sum(d))


from sys import stdin, stdout, stderr, maxsize
tup = lambda : map(int, stdin.readline().split())
I = lambda : int(stdin.readline())
lint = lambda : [int(x) for x in stdin.readline().split()]
S = lambda : stdin.readline().replace('\n', '').strip()
stpr = lambda x: stdout.write(f'{x}' + '\n')
star = lambda x: print(' '.join(map(str, x)))
from collections import defaultdict
for _ in range(I()):
	n = I()
	ls = lint()
	stpr(sum([max(ls[i] - ls[i + 1], 0) for i in range(n - 1)]))


def sol(l):
	ans = 0
	for i in range(1, len(l)):
		ans += max(l[i - 1] - l[i], 0)
	print(ans)
k = int(input())
for i in range(k):
	input()
	lis = list(map(int, input().split(' ')))
	sol(lis)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	ans = 0
	for x in range(n - 2, -1, -1):
		if a[x] > a[x + 1]:
			ans += a[x] - a[x + 1]
	print(ans)


for _ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))[:n]
	k = 0
	s = 0
	for i in range(n):
		s = s + max(0, k - ar[i])
		k = ar[i]
	print(s)


for _ in range(int(input())):
	k = int(input())
	l = list(map(int, input().split()))
	s = 0
	for i in range(1, k):
		s = s + max(0, l[i - 1] - l[i])
	print(s)


import sys
T = int(sys.stdin.readline().strip())
for t in range(0, T):
	n = int(sys.stdin.readline().strip())
	a = list(map(int, sys.stdin.readline().strip().split()))
	ans = 0
	for i in range(1, n):
		if a[i] < a[i - 1]:
			ans = ans + a[i - 1] - a[i]
	print(ans)


import os
import re
import sys
from bisect import bisect, bisect_left, insort, insort_left
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from fractions import gcd
from io import BytesIO, IOBase
from itertools import accumulate, combinations, combinations_with_replacement, groupby, permutations, product
from math import acos, asin, atan, ceil, cos, degrees, factorial, hypot, inf, log2, pi, radians, sin, sqrt, tan
from operator import itemgetter, mul
from string import ascii_lowercase, ascii_uppercase, digits

def inp():
	return int(input())

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

def instr():
	s = input()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())

def main():
	t = inp()
	for _ in range(t):
		n = inp()
		a = inlist()
		a.append(1000000000000000)
		d = a[0]
		ans = 0
		mini = d
		for i in range(1, n + 1):
			if a[i] < a[i - 1]:
				mini = min(a[i], mini)
			else:
				ans += d - mini
				d = a[i]
				mini = d
		print(ans)
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))

def input():
	return sys.stdin.readline().rstrip('\r\n')
main()


def solve(n, a):
	answ = 0
	for i in range(1, n):
		answ += max(a[i - 1] - a[i], 0)
	print(answ)
t = int(input())
while t:
	n = int(input())
	a = [int(i) for i in input().split()]
	solve(n, a)
	t -= 1


import sys

def main():
	t = Iint()
	inf = float('inf')
	for _ in range(t):
		n = Iint()
		a = Ilist()
		ans = sum((a[i - 1] - a[i] for i in range(1, n) if a[i] < a[i - 1]))
		print(ans)
en = enumerate
FIO = 10

def debug(*args, c=6):
	pass
	print('\x1b[3{}m'.format(c), *args, '\x1b[0m', file=sys.stderr)
BUFSIZE = 8 * 1024

def Istr():
	return input()

def Iint():
	return int(input())

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

def Imap():
	return map(int, input().split())

def Plist(li, s=' '):
	print(s.join(map(str, li)))
if not FIO:
	if __name__ == '__main__':
		main()
		exit()
else:
	from io import BytesIO, IOBase
	import os

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))

def input():
	return sys.stdin.readline().rstrip('\r\n')
main()


import sys, math
input = lambda : sys.stdin.readline().rstrip()
for __ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	for i in range(n):
		if i > 0:
			ans += max(0, a[i - 1] - a[i])
	print(ans)


q = int(input())
for _ in range(q):
	n = int(input())
	ans = int(0)
	ar = list(map(int, input().split()))
	for i in range(n - 1):
		if ar[i + 1] < ar[i]:
			ans = ans + ar[i] - ar[i + 1]
	print(ans)


for _ in range(int(input())):
	n = int(input())
	l = [int(j) for j in input().split()]
	s = l[n - 1]
	ans = 0
	for i in range(n - 2, -1, -1):
		if l[i] > s:
			ans += l[i] - s
			s = l[i]
		else:
			s = min(l[i], s)
	print(ans)


t = int(input())
while t:
	t = t - 1
	n = int(input())
	a = list(map(int, input().split()))
	lst = a[0]
	out = 0
	flag = 1
	for i in range(1, n):
		if a[i] < a[i - 1] and flag == 1:
			out += a[i - 1] - a[i]
			lst = a[i - 1]
			flag = 0
		elif a[i] < a[i - 1] and flag == 0:
			out += a[i - 1] - a[i]
			flag = 0
		else:
			flag = 1
	print(out)


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


def main():
	n = int(input())
	for i in range(n):
		solve()

def solve():
	n = int(input())
	arr = list(map(int, input().split()))
	count = 0
	index = 0
	prev = arr[0]
	while index < n:
		if arr[index] < prev:
			count += prev - arr[index]
		prev = arr[index]
		index += 1
	print(count)
main()


import sys
import random
from fractions import Fraction
from math import *

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def finput():
	return float(input())

def tinput():
	return input().split()

def linput():
	return list(input())

def rinput():
	return map(int, tinput())

def fiinput():
	return map(float, tinput())

def flinput():
	return list(fiinput())

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

def trinput():
	return tuple(rinput())

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

def NOYES(fl):
	if fl:
		print('NO')
	else:
		print('YES')

def YESNO(fl):
	if fl:
		print('YES')
	else:
		print('NO')

def main():
	n = iinput()
	q = rlinput()
	print(sum([max(q[i] - q[i + 1], 0) for i in range(n - 1)]))
for TESTING in range(iinput()):
	main()


import sys
from decimal import Decimal
import math
from itertools import combinations, product
import bisect
from collections import Counter, deque, defaultdict
MOD = 10 ** 6 + 7
INF = 10 ** 9
PI = 3.141592653589793

def read_str():
	return sys.stdin.readline().strip()

def read_int():
	return int(sys.stdin.readline().strip())

def read_ints():
	return map(int, sys.stdin.readline().strip().split())

def read_str_list():
	return list(sys.stdin.readline().strip().split())

def read_int_list():
	return list(map(int, sys.stdin.readline().strip().split()))

def lcm(a: int, b: int) -> int:
	return a * b // math.gcd(a, b)

def Main():
	for _ in range(read_int()):
		n = read_int()
		a = read_int_list()
		ans = []
		for i in range(1, n):
			if a[i - 1] > a[i]:
				ans.append(a[i - 1] - a[i])
		print(sum(ans))
Main()


t = int(input(''))
arr = []
for i in range(t):
	int(input(''))
	arr.append(list(map(int, input().split())))
for i in arr:
	n = len(i)
	sign = 0
	for j in range(1, n):
		if i[j] < i[j - 1]:
			sign = 1
			break
	if sign == 0:
		print(0)
		continue
	prb = []
	for j in range(n - 1):
		if i[j] > i[j + 1]:
			prb.append(j)
	if len(prb) == 1:
		val = i[prb[0]]
		ind = prb[0]
		mn = 1000000000000
		for j in range(ind, n):
			mn = min(mn, i[j])
		print(val - mn)
		continue
	cnt = 0
	for j in range(len(prb) - 1):
		a = i[prb[j]]
		b = i[prb[j + 1]]
		idx1 = prb[j]
		idx2 = prb[j + 1]
		mn = 10000000000000
		for k in range(idx1, idx2 + 1):
			mn = min(mn, i[k])
		cnt += a - mn
	sz = len(prb) - 1
	val = i[prb[sz]]
	idx = prb[sz] + 1
	mn = 10000000000000
	for j in (idx, n - 1):
		mn = min(mn, i[j])
	cnt += val - mn
	print(cnt)


for _ in range(int(input())):
	n = int(input())
	a = [int(j) for j in input().split()]
	if len(set(a)) == 1:
		print(0)
	else:
		count = 0
		a = a[::-1]
		for i in range(1, n):
			if a[i] > a[i - 1]:
				count += a[i] - a[i - 1]
		print(count)


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	a = [int(x) for x in input().split()]
	base = a[0]
	count = 0
	for elem in a[1:]:
		if elem < base:
			count += base - elem
		base = elem
	print(count)


t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	high = 0
	low = 0
	count = 0
	i = 0
	while True:
		i += 1
		if i >= n:
			break
		if arr[i - 1] <= arr[i]:
			continue
		if arr[i - 1] > arr[i]:
			high = arr[i - 1]
			while arr[i - 1] > arr[i]:
				i += 1
				if i == n:
					break
			low = arr[i - 1]
			count += high - low
	print(count)


for t in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	a = a[::-1]
	count = 0
	for i in range(n - 1):
		if a[i] < a[i + 1]:
			count += a[i + 1] - a[i]
	print(count)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(j) for j in input().split()]
	ans = 0
	ind = n - 2
	while ind != -1:
		while ind != -1 and arr[ind] <= arr[ind + 1]:
			ind -= 1
		if ind != -1:
			ans += arr[ind] - arr[ind + 1]
			arr[ind + 1] = arr[ind]
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	m = a[0]
	c = 0
	for i in range(n):
		if a[i] > m:
			m = a[i]
		else:
			c = c + (m - a[i])
			m = a[i]
	print(c)


from __future__ import division, print_function
import os, sys
import math
import collections
from itertools import permutations
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

class my_dictionary(dict):

	def __init__(self):
		self = dict()

	def add(self, key, value):
		self[key] = value

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().strip().split(' '))

def msi():
	return map(str, input().strip().split(' '))

def li():
	return list(mi())

def dmain():
	sys.setrecursionlimit(100000000)
	threading.stack_size(40960000)
	thread = threading.Thread(target=main)
	thread.start()
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def getKey(item):
	return item[1]

def sort2(l):
	return sorted(l, key=getKey, reverse=True)

def d2(n, m, num):
	return [[num for x in range(m)] for y in range(n)]

def isPowerOfTwo(x):
	return x and (not x & x - 1)

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def ntl(n):
	return [int(i) for i in str(n)]

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(n - r))

def binary_search(arr, low, high, x):
	if high >= low:
		mid = (high + low) // 2
		if arr[mid] == x:
			return mid
		elif arr[mid] > x:
			return binary_search(arr, low, mid - 1, x)
		else:
			return binary_search(arr, mid + 1, high, x)
	else:
		return -1

def ceil(x, y):
	if x % y == 0:
		return x // y
	else:
		return x // y + 1

def powerMod(x, y, p):
	res = 1
	x %= p
	while y > 0:
		if y & 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

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

def read():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def padded_bin_with_complement(x):
	if x < 0:
		return bin(2 ** 16 - abs(x))[2:].zfill(16)
	else:
		return bin(x)[2:].zfill(16)

def binaryToDecimal(binary):
	binary1 = binary
	(decimal, i, n) = (0, 0, 0)
	while binary != 0:
		dec = binary % 10
		decimal = decimal + dec * pow(2, i)
		binary = binary // 10
		i += 1
	print(decimal)

def CountFrequency(my_list):
	freq = {}
	for item in my_list:
		if item in freq:
			freq[item] += 1
		else:
			freq[item] = 1
	return freq

def pos(a):
	b = [0] * len(a)
	c = sorted(a)
	for i in range(len(a)):
		for j in range(len(a)):
			if c[j] == a[i]:
				b[i] = j
				break
	return b

def smallestDivisor(n):
	if n % 2 == 0:
		return 2
	i = 3
	while i * i <= n:
		if n % i == 0:
			return i
		i += 2
	return n

def commonn(a, b, n):
	c = []
	for i in range(n):
		if a[i] == b[i]:
			c.append('-1')
		else:
			c.append(b[i])
	return c

def primeFactors(n):
	j = []
	while n % 2 == 0:
		j.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			j.append(int(n))
			n = n / i
	if n > 2:
		j.append(int(n))
	return j

def sumdigit(n):
	n = str(n)
	k = 0
	for i in range(len(n)):
		k += int(n[i])
	return k

def question(a, n):
	j = a
	for i in range(n):
		if a[i] == '1':
			j[i] = '0'
		else:
			j[i] = '1'
	j[0, n - 1].reverse()
	return j

def main():
	for _ in range(ii()):
		n = ii()
		a = li()
		res = 0
		for i in range(n - 1):
			if a[n - i - 1] < a[n - i - 2]:
				res += a[n - i - 2] - a[n - i - 1]
		print(res)
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):
	(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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


t = int(input())
while t > 0:
	t = t - 1
	n = int(input())
	a = list(map(int, input().split()))
	s = 0
	for i in range(1, n):
		s += max(a[i - 1] - a[i], 0)
	print(s)


def waterSlide(a, size):
	steps = 0
	for i in range(size - 1):
		if a[i] > a[i + 1]:
			steps += a[i] - a[i + 1]
	return steps
tests = int(input())
for i in range(tests):
	size = int(input())
	slides = list(map(int, input().split()))
	print(waterSlide(slides, size))


import sys
from collections import defaultdict as dd
from collections import Counter as cc
from queue import Queue
import math
import itertools
try:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
except:
	pass
input = lambda : sys.stdin.buffer.readline().rstrip()
for _ in range(int(input())):
	q = int(input())
	w = list(map(int, input().split()))
	k = 0
	for i in range(1, q):
		if w[i] < w[i - 1]:
			k += w[i - 1] - w[i]
	print(k)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	(l1, l2) = ([], [])
	l1.append(l[0])
	for i in range(1, n):
		l1.append(max(l1[-1], l[i]))
	for i in range(n):
		l2.append(l1[i] - l[i])
	x = l2[0]
	ans = 0
	for i in range(1, n):
		ans += max(0, l2[i] - x)
		x = l2[i]
	print(ans)


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


t = int(input())
for i in range(t):
	n = int(input())
	li = list(map(int, input().strip().split()))
	if sorted(li) == li:
		print(0)
	else:
		l = []
		for j in range(1, len(li)):
			if li[j] < li[j - 1]:
				l.append(abs(li[j] - li[j - 1]))
		print(sum(l))


def solve(n, a):
	last = 0
	sol = 0
	prev = 0
	for x in a:
		sol += max(prev - x, 0)
		last = max(last, x)
		prev = x
	return sol
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	print(solve(n, a))


from bisect import bisect_left, bisect_right
from itertools import combinations
from itertools import permutations
from bisect import bisect_left
from math import ceil
from math import radians
from heapq import heapify, heappush, heappop
import bisect
from math import pi
from collections import deque
from math import factorial
from math import log, ceil
from collections import defaultdict
from math import *
from sys import stdin, stdout
import itertools
import os
import sys
import threading
from collections import deque, Counter, OrderedDict, defaultdict
from heapq import *
from fractions import Fraction
mod = int(pow(10, 9) + 7)

def ii():
	return int(input())

def si():
	return str(input())

def mi():
	return map(int, input().split())

def li1():
	return list(mi())

def fii():
	return int(stdin.readline())

def fsi():
	return str(stdin.readline())

def fmi():
	return map(int, stdin.readline().split())

def fli():
	return list(fmi())
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}

def getKey(item):
	return item[0]

def sort2(l):
	return sorted(l, key=getKey)

def d2(n, m, num):
	return [[num for x in range(m)] for y in range(n)]

def isPowerOfTwo(x):
	return x and (not x & x - 1)

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def ntl(n):
	return [int(i) for i in str(n)]

def powerMod(x, y, p):
	res = 1
	x %= p
	while y > 0:
		if y & 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res
graph = defaultdict(list)
visited = [0] * 1000000
col = [-1] * 1000000

def bfs(d, v):
	q = []
	q.append(v)
	visited[v] = 1
	while len(q) != 0:
		x = q[0]
		q.pop(0)
		for i in d[x]:
			if visited[i] != 1:
				visited[i] = 1
				q.append(i)
		print(x)

def make_graph(e):
	d = {}
	for i in range(e):
		(x, y) = mi()
		if x not in d:
			d[x] = [y]
		else:
			d[x].append(y)
		if y not in d:
			d[y] = [x]
		else:
			d[y].append(x)
	return d

def gr2(n):
	d = defaultdict(list)
	for i in range(n):
		(x, y) = mi()
		d[x].append(y)
	return d

def connected_components(graph):
	seen = set()

	def dfs(v):
		vs = set([v])
		component = []
		while vs:
			v = vs.pop()
			seen.add(v)
			vs |= set(graph[v]) - seen
			component.append(v)
		return component
	ans = []
	for v in graph:
		if v not in seen:
			d = dfs(v)
			ans.append(d)
	return ans

def primeFactors(n):
	s = set()
	while n % 2 == 0:
		s.add(2)
		n = n // 2
	for i in range(3, int(sqrt(n)) + 1, 2):
		while n % i == 0 and i % 2 == 1:
			s.add(i)
			n = n // i
	if n > 2 and n % 2 == 1:
		s.add(n)
	return s

def find_all(a_str, sub):
	start = 0
	while True:
		start = a_str.find(sub, start)
		if start == -1:
			return
		yield start
		start += len(sub)

def SieveOfEratosthenes(n, isPrime):
	isPrime[0] = isPrime[1] = False
	for i in range(2, n):
		isPrime[i] = True
	p = 2
	while p * p <= n:
		if isPrime[p] == True:
			i = p * p
			while i <= n:
				isPrime[i] = False
				i += p
		p += 1
	return isPrime

def dijkstra(edges, f, t):
	g = defaultdict(list)
	for (l, r, c) in edges:
		g[l].append((c, r))
	(q, seen, mins) = ([(0, f, ())], set(), {f: 0})
	while q:
		(cost, v1, path) = heappop(q)
		if v1 not in seen:
			seen.add(v1)
			path = (v1, path)
			if v1 == t:
				return (cost, path)
			for (c, v2) in g.get(v1, ()):
				if v2 in seen:
					continue
				prev = mins.get(v2, None)
				next = cost + c
				if prev is None or next < prev:
					mins[v2] = next
					heappush(q, (next, v2, path))
	return float('inf')

def binsearch(a, l, r, x):
	while l <= r:
		mid = l + (r - 1) // 2
		if a[mid]:
			return mid
		elif a[mid] > x:
			l = mid - 1
		else:
			r = mid + 1
	return -1

def readTree(n):
	adj = [set() for _ in range(n)]
	for _ in range(n - 1):
		(u, v) = map(int, input().split())
		adj[u - 1].add(v - 1)
		adj[v - 1].add(u - 1)
	return adj

def treeOrderByDepth(n, adj, root=0):
	parent = [-2] + [-1] * (n - 1)
	ordered = []
	q = deque()
	q.append(root)
	depth = [0] * n
	while q:
		c = q.popleft()
		ordered.append(c)
		for a in adj[c]:
			if parent[a] == -1:
				parent[a] = c
				depth[a] = depth[c] + 1
				q.append(a)
	return (ordered, parent, depth)

def isSubSequence(str1, str2):
	m = len(str1)
	n = len(str2)
	j = 0
	i = 0
	while j < m and i < n:
		if str1[j] == str2[i]:
			j = j + 1
		i = i + 1
	return j == m

def nextPowerOf2(n):
	count = 0
	if n and (not n & n - 1):
		return n
	while n != 0:
		n >>= 1
		count += 1
	return 1 << count

def cou(n):
	c = 0
	while n > 1:
		c += 1
		n //= 2
	return c

def sortsec(l):
	return sorted(l, key=lambda x: x[1])

def BinarySearch(a, x):
	i = bisect_left(a, x)
	if i:
		return i - 1
	else:
		return -1

def subarray(A):
	r = set()
	p = {0}
	for x in A:
		p = {x | y for y in p} | {x}
		r |= p
	return len(r)
for _ in range(ii()):
	n = ii()
	a = li1()
	sum = 0
	for i in range(n - 1, 0, -1):
		if a[i] < a[i - 1]:
			sum += abs(a[i] - a[i - 1])
	print(sum)


t = int(input())
for case in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	out = 0
	for (x, y) in zip(a, a[1:]):
		out += max(0, x - y)
	print(out)


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


t = int(input())
for k in range(0, t):
	n = int(input())
	a = list(map(int, input().strip().split()))[:n]
	if n == 1:
		print(0)
		continue
	max1 = -1
	diff = 0
	for i in range(1, n):
		if a[i] - a[i - 1] < 0:
			diff += a[i - 1] - a[i]
	print(diff)


for t in range(int(input())):
	n = int(input())
	arr = [int(k) for k in input().split()]
	crmx = arr[0]
	ans = 0
	prmo = 0
	mo = 0
	temp = []
	for i in range(n):
		if arr[i] < crmx:
			temp.append(crmx - arr[i])
		else:
			for ele in temp:
				if ele >= mo:
					mo = ele
				else:
					ans += mo - prmo
					prmo = ele
					mo = ele
			ans += mo - prmo
			crmx = arr[i]
			temp = []
			mo = 0
			prmo = 0
	for ele in temp:
		if ele >= mo:
			mo = ele
		else:
			ans += mo - prmo
			prmo = ele
			mo = ele
	ans += mo - prmo
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	m = a[0]
	operations = 0
	ind = 0
	while ind < len(a):
		if m <= a[ind]:
			m = a[ind]
			ind += 1
		else:
			operations += m - a[ind]
			ind += 1
			flag = 0
			while ind < len(a):
				if a[ind - 1] <= a[ind]:
					ind += 1
				else:
					flag = 1
					break
			m = a[ind - 1] if flag == 1 else m
			continue
	print(operations)


n = int(input())
for _ in range(n):
	_ = int(input())
	arr = list(map(int, input().split()))
	MAX = arr[0]
	up = []
	for x in arr:
		MAX = max(MAX, x)
		up.append(MAX - x)
	ans = 0
	for i in range(len(up) - 1):
		if up[i] < up[i + 1]:
			ans += up[i + 1] - up[i]
	print(ans)


t = int(input())
for hh in range(t):
	n = int(input())
	li = [int(i) for i in input().split()]
	i = 0
	count = 0
	while i < len(li) - 1:
		if li[i + 1] < li[i]:
			lig = []
			j = i + 1
			while j < len(li):
				if li[j] > li[j - 1]:
					break
				else:
					lig.append(li[i] - li[j])
					j += 1
			if len(lig) == 1:
				count += lig[0]
			else:
				for i in range(len(lig) - 1):
					count += lig[i + 1] - lig[i]
				count += lig[0]
			i = j
		else:
			i += 1
	print(count)


import math, sys
from collections import defaultdict, Counter, deque
INF = float('inf')
MOD = 10 ** 9 + 7

def gcd(a, b):
	while b:
		(a, b) = (b, a % b)
	return a

def isPrime(n):
	if n <= 1:
		return False
	i = 2
	while i ** 2 <= n:
		if n % i == 0:
			return False
		i += 1
	return True

def primeFactors(n):
	factors = []
	i = 2
	while i ** 2 <= n:
		while n % i == 0:
			factors.append(i)
			n //= i
		i += 1
	if n > 1:
		factors.append(n)
	return factors

def vars():
	return map(int, input().split())

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

def main():
	n = int(input())
	arr = array()
	peak = 0
	ans = 0
	for i in range(n):
		if i < n - 1 and (not peak) and (arr[i] > arr[i + 1]):
			peak = arr[i]
		if i < n - 1 and peak and (arr[i] < arr[i + 1]) or (i == n - 1 and peak):
			ans += peak - arr[i]
			peak = 0
	print(ans)
t = 1
t = int(input())
for _ in range(t):
	main()


def readn():
	return int(input())

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

def readnos():
	return map(int, input().split())

def solve(a, n, ans):
	if n == 1:
		return ans
	i = 0
	j = 0
	while i < n - 1:
		j = i + 1
		if a[i + 1] < a[i]:
			while j < n and a[j] >= a[i]:
				j += 1
			ans = solve(a[i + 1:j], j - i, ans)
			ans += a[i] - a[i + 1]
			for k in range(i + 1, j):
				a[k] = a[i]
		i = j
	return ans
for _ in range(readn()):
	n = readn()
	a = readlist()
	ans = 0
	ans = solve(a, n, ans)
	print(ans)


a = int(input())
for i in range(a):
	b = int(input())
	arr = list(map(int, input().split()))
	crsum = arr[0]
	ans = []
	for i in range(1, len(arr) - 1):
		if arr[i] < arr[i - 1] and arr[i] <= arr[i + 1]:
			ans.append(crsum - arr[i])
			crsum = arr[i]
		if arr[i] > arr[i - 1] and arr[i] >= arr[i + 1]:
			crsum = arr[i]
	if arr[len(arr) - 1] < crsum:
		ans.append(crsum - arr[len(arr) - 1])
	print(sum(ans))


from sys import stdin
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	for i in range(n - 1):
		if a[i] <= a[i + 1]:
			continue
		ans += a[i] - a[i + 1]
	print(ans)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split(' ')))
	i = 0
	j = 0
	res = 0
	while i < len(l):
		while i < len(l) - 1 and l[i] <= l[i + 1]:
			i += 1
		j = i
		while i < len(l) - 1 and l[i] > l[i + 1]:
			i += 1
		res += l[j] - l[i]
		i += 1
	print(res)


import sys
for t in range(0, int(sys.stdin.readline())):
	leng = int(sys.stdin.readline())
	vals = list(map(int, sys.stdin.readline().split()))
	out = 0
	for i in range(0, leng - 1):
		if vals[i] > vals[i + 1]:
			out += vals[i] - vals[i + 1]
	sys.stdout.write(str(out) + '\n')


t = int(input())
for i in range(t):
	count = 0
	n = int(input())
	a = list(map(int, input().split(' ')))
	for i in range(len(a) - 1):
		if a[i] > a[i + 1]:
			count += a[i] - a[i + 1]
	print(count)


from sys import stdin, stdout
input = stdin.readline
for _ in range(int(input())):
	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]
	print(ans)


import sys

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())

def solve():
	n = mints()
	p = 0
	r = 0
	for i in mints():
		if i < p:
			r += p - i
		p = i
	print(r)
for i in range(mint()):
	solve()


def checker(n, lst):
	result = 0
	for i in range(n - 1):
		if lst[i] > lst[i + 1]:
			result += lst[i] - lst[i + 1]
	return result
for _ in range(int(input())):
	m = int(input())
	a = [int(i) for i in input().split()]
	print(checker(m, a))


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


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
			self.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')
from collections import defaultdict as dd, deque as dq
import math, string

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())
MOD = 10 ** 9 + 7

def solve():
	ans = 0
	N = getInt()
	A = getInts()
	for j in range(N - 2, -1, -1):
		ans += max(A[j] - A[j + 1], 0)
	return ans
for _ in range(getInt()):
	print(solve())


TC = int(input())
for tc in range(TC):
	N = int(input())
	A = list(map(int, input().split()))
	result = 0
	min_a = A[-1]
	for i in range(N - 2, -1, -1):
		if A[i] <= min_a:
			min_a = A[i]
		else:
			result += A[i] - min_a
			min_a = A[i]
	print(result)


from collections import deque
from collections import OrderedDict
import math
import sys
import os
import threading
import bisect
import operator
import heapq
from atexit import register
from io import BytesIO
import io
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	answer = 0
	if n == 1:
		print(0)
		continue
	dp = [0] * n
	dp[n - 1] = lis[n - 1]
	for i in range(n - 2, 0, -1):
		dp[i] = dp[i + 1]
		dp[i] = max(dp[i + 1], lis[i])
	lastIncease = 0
	for i in range(n - 1):
		if lis[i] > lis[i + 1]:
			if lastIncease == 0:
				lastIncease = lis[i] - lis[i + 1]
				answer += lastIncease
				lis[i + 1] = lis[i]
			elif lastIncease >= lis[i] - lis[i + 1]:
				if lis[i + 1] + lastIncease > dp[i + 1]:
					lastIncease -= max(lis[i + 1] + lastIncease - dp[i + 1], 0)
					lis[i + 1] = dp[i + 1]
				else:
					lis[i + 1] += lastIncease
			else:
				temp = lastIncease
				lastIncease += lis[i] - lis[i + 1] - lastIncease
				answer += lis[i] - lis[i + 1] - temp
				lis[i + 1] += lastIncease
		else:
			lastIncease = 0
	print(answer)
sys.exit(0)

class Person:

	def __init__(self, name, age):
		self.name = name
		self.age = age
p1 = Person('heelo', 27)
print(help(Person))
age = 26
name = 'Swaroop'
print('Возрас {} -- {} лет'.format(name, age))
print(help(object))


i = int(input())
for _ in range(i):
	k = input()
	inputlist = [int(k) for k in input().split(' ')]
	inputlist.reverse()
	totad = 0
	added = 0
	last = inputlist[0]
	for inputi in inputlist:
		if inputi > last:
			totad += inputi - last
		last = inputi
	print(totad)


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


import math
import heapq
import bisect
import collections
import fractions
import sys
import os
from io import BytesIO, IOBase
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')
mod = 10 ** 9 + 7
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	m = a[0]
	what = a[0]
	ans = 0
	for i in range(1, n):
		if a[i] < a[i - 1]:
			ans += a[i - 1] - a[i]
	print(ans)


for _ in range(int(input())):
	n = int(input())
	num = list(map(int, input().split()))
	pre = num[0]
	out = 0
	for i in range(1, n):
		if num[i] < pre:
			out += pre - num[i]
		pre = num[i]
	print(out)


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


def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().strip().split()))
		minn = a[-1]
		ret = 0
		for i in range(n - 2, -1, -1):
			if a[i] > minn:
				ret += a[i] - minn
			minn = a[i]
		print(ret)
main()


def waterSlide(*args):
	args = list(args)
	no = 0
	i = len(args) - 1
	while i > 0:
		if args[i] < args[i - 1]:
			no = no + args[i - 1] - args[i]
			i = i - 1
		else:
			i = i - 1
	return no
t = int(input())
for i in range(t):
	n = int(input())
	ht = list(map(int, input().split()))
	print(waterSlide(*ht))


from sys import stdin, stdout

def find(arr, N):
	k = 0
	arr.reverse()
	for i in range(N - 1):
		k += max(0, arr[i + 1] - arr[i])
	return k

def main():
	for _ in range(int(stdin.readline())):
		N = int(stdin.readline())
		arr = list(map(int, stdin.readline().split()))
		print(find(arr, N))
main()


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	ops = 0
	if len(set(arr)) == 1:
		print(0)
	else:
		for i in range(n - 1, 0, -1):
			if arr[i] < arr[i - 1]:
				ops += arr[i - 1] - arr[i]
		print(ops)


t = int(input())
for i in range(t):
	n = int(input())
	array = [int(j) for j in input().split()]
	r = 0
	array.reverse()
	for j in range(0, n - 1):
		if array[j] < array[j + 1]:
			r = r + array[j + 1] - array[j]
	print(r)


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


t = int(input())
for _ in range(t):
	n = int(input())
	list1 = list((int(n) for n in input().split()))
	ans = 0
	for i in range(n - 1):
		ans += max(list1[i] - list1[i + 1], 0)
	print(ans)


for _ in range(int(input())):
	n = int(input())
	lst = list(map(int, input().split()))
	counter = 0
	for i in range(n - 1, 0, -1):
		if lst[i] < lst[i - 1]:
			counter += lst[i - 1] - lst[i]
	print(counter)


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


import math
import collections
from sys import stdin, stdout, setrecursionlimit
from bisect import bisect_left as bsl
from bisect import bisect_right as bsr
import heapq as hq
setrecursionlimit(2 ** 20)
t = 1
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().rstrip().split()))
	mx = -1
	ans = 0
	for i in range(1, n):
		if a[i] >= a[i - 1]:
			continue
		else:
			ans += a[i - 1] - a[i]
	print(ans)


t = int(input())

def cnt(a, low, high, d):
	ans = 0
	s = 0
	prev = -1
	for i in range(high, low - 1, -1):
		if prev != a[i]:
			prev = a[i]
			ans += d - s - a[i]
			s += d - s - a[i]
	return ans
while t:
	n = int(input())
	a = input().split()
	a = list(map(int, a))
	ans = 0
	prev = -1
	i = 0
	while i < n:
		if a[i] >= prev:
			prev = a[i]
			i += 1
		else:
			j = i
			last = prev
			prev = a[i]
			while j < n and a[j] >= prev and (a[j] < last):
				prev = a[j]
				j += 1
			ans += cnt(a, i, j - 1, last)
			i = j
	print(ans)
	t -= 1


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	i = 1
	greatest = a[0]
	smallest = a[0]
	operations = 0
	current = a[0]
	while i != n:
		if a[i] >= current:
			operations += greatest - smallest
			greatest = a[i]
			smallest = a[i]
		else:
			smallest = a[i]
		current = a[i]
		i += 1
	if greatest != a[n - 1]:
		operations += greatest - smallest
	print(operations)


for i in range(int(input())):
	(n, ar) = (int(input()), list(map(int, input().split())))
	x = 0
	ans = 0
	for y in ar:
		ans += max(0, x - y)
		x = y
	print(ans)


from sys import stdin
inp = lambda : stdin.readline().strip()
t = int(inp())
for _ in range(t):
	n = int(inp())
	a = [int(x) for x in inp().split()]
	a.reverse()
	last = 0
	ans = 0
	for i in range(n - 1):
		if a[i] < a[i + 1]:
			ans += max(0, a[i + 1] - a[i])
			a[i] += max(0, a[i + 1] - a[i])
	print(ans)


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for _ in range(t):
	n = int(input())
	b = list(map(int, input().split()))
	ans = 0
	for i in range(n):
		if i != 0 and b[i] < b[i - 1]:
			ans += b[i - 1] - b[i]
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	c = 0
	k = n - 1
	while k > 0:
		if a[k - 1] > a[k]:
			c += a[k - 1] - a[k]
		k -= 1
	print(c)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	out = 0
	for i in range(1, n):
		out += max(0, arr[i - 1] - arr[i])
	print(out)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	dp = [0] * n
	ans = 0
	for i in range(1, n):
		if arr[i] < arr[i - 1] and dp[i - 1] == 0:
			dp[i] = arr[i - 1] - arr[i]
		elif arr[i] < arr[i - 1]:
			dp[i] = arr[i - 1] - arr[i]
	print(sum(dp))


a = int(input())
for i in range(a):
	s = int(input())
	z = list(map(int, input().split()))
	total = 0
	for i in range(len(z) - 2, -1, -1):
		if z[i] > z[i + 1]:
			total += z[i] - z[i + 1]
	print(total)


import math, sys, bisect, heapq
from collections import defaultdict, Counter, deque
from itertools import groupby, accumulate
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda : map(int, input().split())
alele = lambda : list(map(int, input().split()))

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)]
MOD = 1000000000 + 7

def Y(c):
	print(['NO', 'YES'][c])

def y(c):
	print(['no', 'yes'][c])

def Yy(c):
	print(['No', 'Yes'][c])
for _ in range(int(input())):
	N = int(input())
	A = alele()
	Ans = 0
	for i in range(1, N):
		if A[i - 1] > A[i]:
			Ans += A[i - 1] - A[i]
	print(Ans)


for t in range(int(input())):
	n = int(input())
	an = list(map(int, input().split()))[::-1]
	ans = 0
	for i in range(len(an) - 1):
		if an[i] < an[i + 1]:
			ans += an[i + 1] - an[i]
	print(ans)


from functools import reduce
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def arr():
	return [int(i) for i in input().split()]

def sarr():
	return [int(i) for i in input()]

def inn():
	return int(input())
mo = 1000000007
for _ in range(int(input())):
	n = inn()
	a = arr()
	mx = a[0]
	bal = 0
	ans = 0
	for i in range(1, n):
		res = a[i] - a[i - 1]
		if res < 0:
			val = abs(res) - bal
			if val <= 0:
				bal = abs(res)
				a[i] = a[i - 1]
			else:
				ans += val
				bal = abs(res)
				a[i] = a[i - 1]
		else:
			bal = 0
	print(ans)


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


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


for case in range(int(input())):
	n = int(input())
	heights = [i for i in map(int, input().split())]
	diffs = [heights[i + 1] - heights[i] for i in range(n - 1)]
	print(sum((j for j in diffs if j < 0)) * -1)


n = int(input())
for i in range(n):
	m = int(input())
	a = [int(i) for i in input().split()]
	max = a[len(a) - 1]
	sum = 0
	for j in range(len(a) - 1, -1, -1):
		if a[j] > max:
			sum = sum + (a[j] - max)
		max = a[j]
	print(sum)


t = int(input())
for tt in range(t):
	n = int(input())
	lst = list(map(int, input().split()))
	ele = lst[n - 1]
	total = 0
	for i in range(n - 2, -1, -1):
		if lst[i] <= ele:
			ele = min(lst[i], ele)
		else:
			total += lst[i] - ele
			ele = lst[i]
	print(total)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ma = a[0]
	b = [0] * n
	c = [0] * n
	res = 0
	for i in range(1, n):
		if a[i] >= ma:
			ma = a[i]
			continue
		b[i] = ma - a[i]
		res += max(0, b[i] - b[i - 1])
	print(res)


from collections import Counter
import math
import sys
from bisect import bisect, bisect_left, bisect_right

def input():
	return sys.stdin.readline().strip()

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def mod():
	return 10 ** 9 + 7
for i in range(INT()):
	n = INT()
	arr = LIST()
	ans = 0
	for i in range(1, n):
		if arr[i - 1] > arr[i]:
			ans += arr[i - 1] - arr[i]
	print(ans)


from collections import *
from sys import *
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	cn = 0
	for i in range(1, n):
		if a[i] < a[i - 1]:
			cn += a[i - 1] - a[i]
	stdout.write(str(cn) + '\n')


for test in range(int(input())):
	n = int(input())
	l = list(map(int, input().strip().split(' ')))
	nax = 0
	i = 0
	count = 0
	while i < len(l) - 1:
		if l[i] <= l[i + 1]:
			i += 1
		else:
			nax = l[i]
			count += nax - l[i + 1]
			i += 1
	print(count)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split(' ', n - 1)))
	count = 0
	for i in range(1, len(arr)):
		if arr[i - 1] > arr[i]:
			count = count + (arr[i - 1] - arr[i])
	print(count)


import math
from collections import *
import sys
from functools import reduce
import time
from itertools import groupby

def input():
	return sys.stdin.readline()

def get_ints():
	return map(int, input().strip().split())

def get_list():
	return list(get_ints())

def get_string():
	return list(input().strip().split())

def printxsp(*args):
	return print(*args, end='')

def printsp(*args):
	return print(*args, end=' ')
for _test_ in range(int(input())):
	n = int(input())
	li = get_list()
	ans = 0
	for i in range(n - 1, 0, -1):
		if li[i] < li[i - 1]:
			ans += li[i - 1] - li[i]
	print(ans)


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


for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	i = 1
	operations = 0
	end_valley = 0
	while i < len(a):
		if a[i - 1] > a[i]:
			lowest = a[i]
			j = i
			while j < len(a) and a[j] <= a[i - 1]:
				lowest = min(lowest, a[j])
				if j + 1 < len(a) and max(a[j - 1], a[j + 1]) < a[j]:
					operations += a[j] - lowest
					lowest = a[j]
				j += 1
			operations += a[i - 1] - lowest
			i = j + 1
		else:
			i += 1
	print(operations)


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	c = 0
	for i in range(1, n):
		if a[i] < a[i - 1]:
			c += a[i - 1] - a[i]
	print(c)


for i in range(int(input())):
	n = input()
	n = int(n)
	l = [int(x) for x in input().split()]
	hu = 0
	maxo = l[0]
	for i in range(1, n):
		if l[i] < maxo:
			hu += maxo - l[i]
			maxo = l[i]
		elif l[i] > maxo:
			maxo = l[i]
	print(hu)


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


def solve(a, n):
	op = 0
	for i in range(n - 1):
		if a[i] > a[i + 1]:
			op += a[i] - a[i + 1]
	return op
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	print(solve(arr, n))


for _ in range(int(input())):
	n = int(input())
	arr = [int(j) for j in input().split()]
	count = 0
	arr.reverse()
	maxi = arr[0]
	for i in range(1, n):
		if arr[i] > arr[i - 1]:
			count += arr[i] - arr[i - 1]
	print(count)


for _ in range(int(input())):
	n = int(input())
	ai = list(map(int, input().split()))
	mini = 0
	maxi = 0
	flag = 0
	ans = 0
	for i in range(1, n):
		if ai[i] < ai[i - 1]:
			mini = ai[i]
			if flag == 0:
				maxi = ai[i - 1]
				flag = 1
		else:
			if flag == 1:
				ans += maxi - mini
			flag = 0
	if flag == 1:
		ans += maxi - mini
	print(ans)


for testcases in range(int(input())):
	num = int(input())
	l = list(map(int, input().split()))
	ans = 0
	maxi = l[0]
	mini = l[0]
	for i in range(1, num):
		if l[i] < maxi:
			ans += maxi - l[i]
			maxi = l[i]
		elif l[i] > maxi:
			maxi = l[i]
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l.reverse()
	s = 0
	for i in range(n - 1):
		if l[i] < l[i + 1]:
			s += l[i + 1] - l[i]
	print(s)


for _ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	stack = []
	for i in range(1, n):
		if ar[i - 1] > ar[i]:
			stack.append(i)
	ans = 0
	for i in reversed(stack):
		ans += ar[i - 1] - ar[i]
	print(ans)


import sys
import bisect
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	cnt = 0
	for i in range(n - 1):
		cnt += max(l[i] - l[i + 1], 0)
	print(cnt)


t = int(input())

def doWork(a):
	out = 0
	for i in range(1, len(a)):
		if a[i - 1] > a[i]:
			out += a[i - 1] - a[i]
	return out
for i in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	print(doWork(a))


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


kase = int(input().strip())
while kase > 0:
	kase = kase - 1
	n = map(int, input().strip().split())
	a = list(map(int, input().split()))
	ans = 0
	for (i, aj) in enumerate(a[1:]):
		if a[i] > aj:
			ans = ans + a[i] - aj
	print(ans)


import collections
t = int(input().strip(' '))
for _ in range(t):
	n = int(input().strip(' '))
	arr = list(map(int, input().strip(' ').split(' ')))
	pre = arr[0]
	ans = 0
	for i in range(n):
		if arr[i] < pre:
			ans += pre - arr[i]
		pre = arr[i]
	print(ans)


for i in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	a = []
	c = 0
	z = 0
	for i in range(n - 1):
		if l[i] > l[i + 1]:
			a.append(l[i + 1])
			if z < l[i]:
				z = l[i]
		elif len(a) != 0:
			c += z - min(a)
			z = 0
			a = []
	if len(a) != 0:
		c += z - min(a)
	print(c)


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


def solution(arr):
	ans = 0
	for i in range(1, len(arr)):
		if arr[i - 1] > arr[i]:
			ans = ans + arr[i - 1] - arr[i]
	return ans
for _ in range(int(input())):
	n = int(input())
	arr = [int(x) for x in input().split()]
	print(solution(arr))


def solve():
	n = int(input())
	arr = [int(i) for i in input().split()]
	ok = 0
	ans = 0
	for i in range(0, len(arr) - 1):
		if arr[i] > arr[i + 1]:
			ans += arr[i] - arr[i + 1]
	print(ans)
test = int(input())
while test:
	solve()
	test -= 1


for u in range(int(input())):
	n = int(input())
	x = [int(w) for w in input().split()]
	if x == sorted(x):
		print(0)
	else:
		ans = 0
		for i in range(1, n):
			if x[i - 1] > x[i]:
				ans += abs(x[i] - x[i - 1])
		print(ans)


res = ''
for _ in range(int(input())):
	input()
	a = [int(x) for x in input().split()]
	a = a[::-1]
	r = 0
	for (r1, r2) in zip(a, a[1:]):
		if r2 > r1:
			r += r2 - r1
	res += f'{r}\n'
print(res)


from collections import deque
t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	s = deque()
	s.append(l[0])
	c = 0
	for i in range(1, len(l)):
		if s[-1] > l[i]:
			s.append(l[i])
		else:
			while len(s) != 0 and s[-1] <= l[i]:
				k = s.pop()
				if len(s) != 0 and s[-1] <= l[i]:
					c += s[-1] - k
			if len(s) == 0:
				s.append(l[i])
			else:
				c += l[i] - k
				s.append(l[i])
	while len(s) != 1:
		k = s.pop()
		c += s[-1] - k
	print(c)


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


test = int(input())
for i in range(test):
	n = int(input())
	vals = [int(x) for x in input().split()]
	if len(vals) == 1:
		print(0)
		continue
	largest = vals[0]
	peaks = [vals[0]]
	total = 0
	gap = 0
	if vals[1] > vals[0]:
		increasing = True
	else:
		increasing = False
	for i in range(1, n):
		if vals[i] > vals[i - 1] and increasing == False:
			peaks.append(vals[i - 1])
			increasing = True
		elif vals[i] < vals[i - 1] and increasing == True:
			peaks.append(vals[i - 1])
			increasing = False
	if peaks[-1] != vals[-1]:
		peaks.append(vals[-1])
	largest = peaks[0]
	for i in range(len(peaks) - 1):
		if peaks[i] > largest:
			largest = peaks[i]
		elif peaks[i] < largest and peaks[i] < peaks[i + 1]:
			if largest > peaks[i + 1]:
				total += peaks[i + 1] - peaks[i]
			else:
				total += largest - peaks[i]
	if peaks[-1] < largest:
		total += largest - peaks[-1]
	print(total)


try:
	for _ in range(int(input())):
		n = int(input())
		arr = list(map(int, input().split()))
		c = 0
		tmp = []
		for i in range(0, n):
			if i < n - 1 and arr[i + 1] <= arr[i]:
				tmp.append(arr[i + 1])
				tmp.append(arr[i])
			elif tmp:
				c += max(tmp) - min(tmp)
				tmp.clear()
		print(c)
except EOFError:
	pass


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	i = 0
	while i < n - 1:
		if a[i] <= a[i + 1]:
			i = i + 1
			pass
		else:
			k = a[i]
			p = a[i + 1]
			j = i + 1
			while j < n:
				if a[j] >= k:
					s = j
					break
				if a[j] <= p:
					p = a[j]
				else:
					ans = ans + a[j] - p
					p = a[j]
				j = j + 1
			else:
				s = n - 1
			ans = ans + (k - p)
			i = s
	print(ans)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	stack = arr[0]
	maxx = -10
	ans = 0
	for i in range(1, n):
		if arr[i] < stack:
			if stack > maxx:
				maxx = stack
			stack = arr[i]
		elif arr[i] >= stack:
			if maxx != -10:
				ans += abs(maxx - stack)
			stack = arr[i]
			maxx = -10
	if maxx != -10:
		ans += abs(maxx - stack)
	print(ans)


for _ in range(int(input())):
	n = int(input())
	array = list(map(int, input().split()))
	pre = array[0]
	temp = []
	result = 0
	for i in array:
		if i < pre:
			temp.append(pre)
			temp.append(i)
		elif i >= pre:
			try:
				temp.sort()
				minimum = temp[0]
				maximum = temp[-1]
				result += maximum - minimum
			except:
				minimum = 0
			temp = []
		pre = i
	try:
		if array[-1] < array[-2]:
			try:
				temp.sort()
				minimum = temp[0]
				maximum = temp[-1]
				result += maximum - minimum
			except:
				pass
	except:
		pass
	print(result)


cases = int(input())
for case in range(cases):
	n = int(input())
	arr = list(map(int, input().split(' ')))
	nxt = [0] * n
	mx = arr[0]
	for i in range(1, n):
		mx = max(mx, arr[i])
		if arr[i] < arr[i - 1]:
			nxt[i] = arr[i - 1] - arr[i]
	cnt = 0
	for i in range(1, n):
		cnt += nxt[i]
	print(cnt)


def _i():
	return int(input())

def _il():
	return [int(x) for x in input().split()]

def _iil():
	n = _i()
	a = _il()
	assert n == len(a)
	return a

def solve(a):
	last = a[0]
	b = [0]
	for x in a[1:]:
		if x < last:
			b.append(last - x)
		else:
			b.append(0)
			last = x
	return sum((y - x if y > x else 0 for (x, y) in zip(b, b[1:])))
for _ in range(int(input())):
	a = _iil()
	print(solve(a))


from functools import lru_cache
from sys import stdin, stdout
import sys
from math import *
input = stdin.readline
for __ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	b = [0] * n
	b[0] = ar[0]
	ans = 0
	for i in range(1, n):
		if ar[i] < b[i - 1]:
			if ar[i] < ar[i - 1]:
				ans += ar[i - 1] - ar[i]
				b[i] = b[i - 1]
			else:
				b[i] = b[i - 1]
		else:
			b[i] = ar[i]
	print(ans)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
t = int(input())
for test in range(t):
	n = int(input())
	nums = [int(x) for x in input().split()]
	ans = 0
	for i in range(1, n):
		if nums[i] < nums[i - 1]:
			delta = nums[i - 1] - nums[i]
			ans += delta
	print(ans)


def solve():
	n = int(input())
	arr = [int(x) for x in input().split()][::-1]
	operations = 0
	for i in range(n - 1):
		operations += max(arr[i + 1] - arr[i], 0)
	print(operations)
for _ in range(int(input())):
	solve()


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	m = 0
	for i in range(n - 1):
		m += max(l[i] - l[i + 1], 0)
	print(m)


t = int(input())
while t:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	cnt = [0] * n
	ans = 0
	max_tem = 0
	for i in range(1, n):
		if a[i] >= a[i - 1]:
			ans += max_tem
			max_tem = 0
		else:
			max_tem += a[i - 1] - a[i]
	ans += max_tem
	print(ans)


from sys import stdin, stdout
import math, sys, heapq
from itertools import permutations, combinations
from collections import defaultdict, deque, OrderedDict
from os import path
import random
import bisect as bi

def yes():
	print('YES')

def no():
	print('NO')
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

	def I():
		return int(input())

	def In():
		return map(int, input().split())
else:

	def I():
		return int(stdin.readline())

	def In():
		return map(int, stdin.readline().split())
sys.setrecursionlimit(1500)

def dict(a):
	d = {}
	for x in a:
		if d.get(x, -1) != -1:
			d[x] += 1
		else:
			d[x] = 1
	return d

def find_gt(a, x):
	i = bi.bisect_right(a, x)
	if i != len(a):
		return i
	else:
		return -1

def main():
	try:
		n = I()
		l = list(In())
		uptilmax = 0
		ans = 0
		last = l[-1]
		for x in range(n - 2, -1, -1):
			if l[x] > +l[x + 1]:
				uptilmax += l[x] - l[x + 1]
		print(uptilmax)
	except:
		pass
M = 998244353
P = 1000000007
for _ in range(I()):
	main()


import io
import os
from collections import Counter, defaultdict, deque

def solve(N, A):
	chunks = []
	for x in A:
		if chunks and chunks[-1][-1] <= x:
			chunks[-1].append(x)
		else:
			chunks.append([x])
	cost = 0
	for i in reversed(range(len(chunks))):
		if i != 0:
			chunk = chunks[i]
			prevChunk = chunks[i - 1]
			cost += prevChunk[-1] - chunk[0]
	return cost
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = int(input())
for tc in range(1, TC + 1):
	(N,) = [int(x) for x in input().split()]
	A = [int(x) for x in input().split()]
	ans = solve(N, A)
	print(ans)


T = int(input())
for case in range(T):
	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]
	print(ans)


t = int(input())
while t:
	n = int(input())
	nl = list(map(int, input().split()))
	steps = 0
	for i in range(n - 1):
		if nl[i] > nl[i + 1]:
			steps += nl[i] - nl[i + 1]
	print(steps)
	t -= 1


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


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


t = int(input())
for i in range(t):
	n = int(input())
	b = list(map(int, input().split()))
	j = 1
	ans = 0
	m = b[0]
	while j < n:
		if b[j] >= b[j - 1]:
			m = b[j]
			pass
		else:
			if b[j] >= m:
				pass
			else:
				ans += m - b[j]
			m = b[j]
			b[j] = b[j - 1]
		j += 1
	print(ans)


import sys, os
from io import BytesIO, IOBase
import collections, itertools, bisect, heapq, math, string
from decimal import *
BUFSIZE = 8192
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')

def main():
	t = int(input())
	for i in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		ans = 0
		for j in range(1, len(a)):
			ans += max(0, a[j - 1] - a[j])
		print(ans)
main()


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))

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


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	cnt = 0
	for i in range(n):
		if i == n - 1:
			break
		elif a[i + 1] < a[i]:
			cnt += a[i] - a[i + 1]
	print(cnt)


def read_int():
	n = int(input())
	return n

def read_ints():
	ints = [int(x) for x in input().split(' ')]
	return ints

def solve(n, a):
	b = a[::-1]
	opr = 0
	for i in range(n - 1):
		if b[i] < b[i + 1]:
			opr += b[i + 1] - b[i]
	return opr
t = read_int()
for case in range(t):
	n = read_int()
	a = read_ints()
	sol = solve(n, a)
	print(sol)


for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	max1 = lis[0]
	operations = 0
	i = 1
	while i < len(lis):
		if lis[i] >= lis[i - 1]:
			max1 = max(lis[i], max1)
			i += 1
			continue
		else:
			min1 = lis[i]
			i += 1
			while i < len(lis) and lis[i] <= lis[i - 1]:
				min1 = lis[i]
				i += 1
			operations += max1 - min1
			max1 = -float('Inf')
	print(operations)


T = int(input())
for test in range(T):
	n = int(input())
	a = [int(x) for x in input().split()]
	count = 0
	for i in range(n - 1, 0, -1):
		count += max(0, a[i - 1] - a[i])
	print(count)


for _ in range(int(input())):
	n = int(input())
	lst = list(map(int, input().split()))
	lst1 = []
	for i in range(1, n):
		if lst[i] < lst[i - 1]:
			lst1.append(i - 1)
	l = len(lst1)
	ct = 0
	i = 1
	while i <= l:
		ct += lst[lst1[-i]] - lst[lst1[-i] + 1]
		lst[lst1[-i] + 1] = lst[lst1[-i]]
		i += 1
	print(ct)


for _ in range(int(input())):
	n = int(input())
	sequence = list(map(int, input().split()))
	if n == 1:
		print(0)
		continue
	operations = 0
	not_falling = False
	for index in range(n - 1):
		if not_falling:
			if sequence[index] <= sequence[index + 1]:
				continue
			else:
				not_falling = False
		if sequence[index] > sequence[index + 1]:
			operations += sequence[index] - sequence[index + 1]
			not_falling = True
	print(operations)


(z, zz) = (input, lambda : list(map(int, z().split())))
(szz, dgraphs, mod) = (lambda : sorted(zz()), {}, 10 ** 9 + 7)
from string import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f
from bisect import bisect as bs
from bisect import bisect_left as bsl
from itertools import accumulate as ac

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)

def prime(x):
	p = ceil(x ** 0.5) + 1
	for i in range(2, p):
		if x % i == 0 and x != 2:
			return 0
	return 1

def dfs(u, visit, graph):
	visit[u] = True
	for i in graph[u]:
		if not visit[i]:
			dfs(i, visit, graph)
num = int(z())
for i in range(num):
	n = int(z())
	l = zz()
	mx = l[n - 1]
	ans = 0
	for i in range(2, n + 1):
		p = l[n - i]
		if p >= mx:
			ans += p - mx
		mx = p
	print(ans)


list_ans = []
for _ in range(int(input())):
	n = int(input())
	list1 = list(map(int, input().split()))
	ans = 0
	for i in range(n - 1):
		if list1[i] > list1[i + 1]:
			ans += list1[i] - list1[i + 1]
	list_ans.append(ans)
print(*list_ans, sep='\n')


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	l = 0
	s = 0
	p = 0
	for i in a:
		s += max(p - i, 0)
		l += max(l, i)
		p = i
	print(s)


for test in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	for i in range(n - 1, 0, -1):
		if arr[i] == arr[i - 1]:
			arr.pop(i)
	n = len(arr)
	if n == 1:
		print(0)
	else:
		pp = [0] * n
		if arr[0] > arr[1]:
			pp[0] = 1
		for i in range(1, n - 1):
			if arr[i - 1] > arr[i] and arr[i] < arr[i + 1]:
				pp[i] = -1
			elif arr[i - 1] < arr[i] and arr[i] > arr[i + 1]:
				pp[i] = 1
		if arr[-1] < arr[-2]:
			pp[-1] = -1
		ans = 0
		posp = -1
		for i in range(n):
			if pp[i] == 1:
				posp = i
			elif pp[i] == -1:
				ans += arr[posp] - arr[i]
		print(ans)


import sys, math
import io, os
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

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
INF = float('inf')
mod = int(1000000000.0) + 7
for t in range(int(data())):
	n = int(data())
	a = mdata()
	m = a[0]
	ans = 0
	for i in range(1, n):
		m = max(m, a[i])
		if a[i] < a[i - 1]:
			ans += a[i - 1] - a[i]
	out(ans)


t = int(input())
for i in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	A.append(1000000007)
	ans = 0
	i = 0
	while i < n:
		if A[i] > A[i + 1]:
			j = i
			while i < n and A[i + 1] <= A[i]:
				i += 1
			ans += A[j] - A[i]
		else:
			i += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	li = list(map(int, input().split()))
	s = 0
	for i in range(1, len(li)):
		s += max(0, li[i - 1] - li[i])
	print(s)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	i = 1
	now = a[0]
	ans = 0
	while i < n:
		if a[i] < a[i - 1]:
			j = i
			ma = a[j]
			while j < n:
				if a[i] <= a[j] and i != j:
					break
				if a[j] < a[j - 1]:
					ans += a[j - 1] - a[j]
					ma = max(a[j], ma)
				j += 1
			ans = ans + (a[i] - ma)
			i = j
		i = i + 1
	print(ans)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	ans = 0
	for i in range(n - 1):
		if a[i] > a[i + 1]:
			ans += a[i] - a[i + 1]
	print(ans)


import sys
input = sys.stdin.readline
import heapq
import copy
import math
import decimal

def inp():
	return int(input())

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

def insr2():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())

def pr_list(a):
	print(*a, sep=' ')

def main():
	tests = inp()
	mod = 1000000007
	limit = 10 ** 18
	ans = 0
	stack = []
	hashm = {}
	arr = []
	heapq.heapify(arr)
	for test in range(tests):
		n = inp()
		a = inlt()
		ans = 0
		mini = a[0]
		for i in range(1, n):
			if a[i] >= mini:
				mini = a[i]
				continue
			if a[i] < a[i - 1]:
				ans = ans + a[i - 1] - a[i]
		print(ans)
main()


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	a = a[::-1]
	op = 0
	for x in range(n - 1):
		if a[x] < a[x + 1]:
			op += a[x + 1] - a[x]
	print(op)


t = int(input())
for j in range(t):
	n = int(input())
	(*a,) = map(int, input().split())
	a = a[::-1]
	c = 0
	for i in range(n - 1):
		if a[i + 1] > a[i]:
			c += a[i + 1] - a[i]
	print(c)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	c = 0
	i = 0
	idx = 0
	while i < n - 1:
		if l[i] > l[i + 1]:
			idx = i
			for i in range(idx + 1, n - 1):
				if l[i] < l[i + 1]:
					break
			end = i + 1
			c += l[idx] - min(l[idx:end + 1])
			i += 1
		else:
			i += 1
	print(c)


def number(n, arr):
	c = 0
	i = 1
	while i < n:
		if array[i] < array[i - 1]:
			c += array[i - 1] - array[i]
		i += 1
	return c
t = int(input())
for i in range(t):
	n = int(input())
	array = list(map(int, input().split()))
	print(number(n, array))


t = int(input())
for i in range(t):
	u = int(input())
	l = list(map(int, input().split()))
	ans = 0
	for i in range(1, len(l)):
		if l[i] >= l[i - 1]:
			continue
		else:
			ans = ans + l[i - 1] - l[i]
	print(ans)


t = int(input())
for tt in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	i = 0
	while i < n - 1:
		if a[i] > a[i + 1]:
			break
		i += 1
	if i >= n - 2:
		print(a[i] - min(a[i:]))
		continue
	j = i
	res = 0
	highest = a[i]
	while j < n - 1:
		while j < n - 1 and a[j] >= a[j + 1]:
			j += 1
		mi = a[j]
		while j < n - 1 and a[j] <= a[j + 1]:
			j += 1
		res += min(highest, a[j]) - mi
		highest = max(highest, a[j])
	res += max(0, highest - a[n - 1])
	print(res)


def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		s = list(map(int, input().split()))
		if n == 1:
			print(0)
			continue
		for i in range(n - 1):
			if s[i + 1] < s[i]:
				start = i + 1
				s.append(s[i])
				break
		else:
			print(0)
			continue
		mm = s[start - 1]
		cnt = 0
		for i in range(start, n):
			if s[i] > mm:
				mm = s[i]
				s[n] = mm
			if s[i + 1] > s[i]:
				if s[i + 1] > mm:
					cnt += mm - s[i]
				else:
					cnt += s[i + 1] - s[i]
		print(cnt)
main()


import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
	N = int(input())
	A = list(map(int, input().split()))
	B = [0]
	mv = A[0]
	for i in range(1, N):
		if A[i] < mv:
			B.append(mv - A[i])
		else:
			B.append(0)
			mv = A[i]
	B.append(0)
	i = 0
	ans = 0
	mv = B[0]
	for i in range(N + 1):
		if B[i] >= mv:
			mv = B[i]
		else:
			ans = ans + mv
			mv = B[i]
			ans = ans - mv
	print(ans)


for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split(' ')))
	i = n - 1
	count = 0
	while i > 0:
		j = i
		while j > 0 and a[j - 1] <= a[j]:
			j -= 1
		if j > 0 and a[j - 1] > a[j]:
			count += a[j - 1] - a[j]
		i = j - 1
	print(count)


import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
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')
ALPHA = 'abcdefghijklmnopqrstuvwxyz'
M = 10 ** 9 + 7
EPS = 1e-06

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
for _ in range(Int()):
	n = Int()
	a = array()
	i = 1
	curMax = a[0]
	steps = 0
	while i < n:
		if a[i] < curMax:
			l = a[i]
			i += 1
			while i < n and a[i] < a[i - 1]:
				l = min(a[i], l)
				i += 1
			try:
				M = a[i]
			except:
				M = curMax
			steps += M - l + curMax - M
			curMax = M
		else:
			curMax = a[i]
			i += 1
	print(steps)


for _ in range(int(input())):
	N = int(input())
	array = [int(x) for x in input().split()]
	counter = 0
	for i in range(1, N):
		if array[i] < array[i - 1]:
			counter += abs(array[i] - array[i - 1])
	print(counter)


def solve(x):
	s = 0
	for j in range(1, len(x)):
		if x[j] < x[j - 1]:
			s += x[j - 1] - x[j]
	return s
for i in range(int(input())):
	x = int(input())
	l = list(map(int, input().split()))
	ans = solve(l)
	print(ans)


from time import time
from random import randint

def solve(arr):
	count = 0
	arr = arr[::-1]
	for i in range(len(arr) - 1):
		if arr[i] < arr[i + 1]:
			count += arr[i + 1] - arr[i]
	print(count)

def submit():
	for case in range(int(input())):
		leng = int(input())
		array = list(map(int, input().split()))
		solve(array)
submit()


t = int(input())
for test in range(0, t):
	n = int(input())
	heights = list(map(int, input().split(' ')))
	result = 0
	stack = [heights[0]]
	for height in heights:
		if height > stack[-1]:
			result += stack[0] - stack[-1]
			stack.clear()
		stack.append(height)
	result += stack[0] - stack[-1]
	print(result)


import sys
import math
import collections
import operator as op
from collections import deque
from math import gcd, inf, sqrt, pi, cos, sin, ceil, log2
from bisect import bisect_right, bisect_left
from functools import reduce
from sys import stdin, stdout, setrecursionlimit
setrecursionlimit(2 ** 20)

def factorial(n):
	if n == 0:
		return 1
	return n * factorial(n - 1)

def ncr(n, r):
	r = min(r, n - r)
	numer = reduce(op.mul, range(n, n - r, -1), 1)
	denom = reduce(op.mul, range(1, r + 1), 1)
	return numer // denom

def prime_factors(n):
	i = 2
	factors = []
	while i * i <= n:
		if n % i:
			i += 1
		else:
			n //= i
			factors.append(i)
	if n > 1:
		factors.append(n)
	return list(factors)

def sumDigits(no):
	return 0 if no == 0 else int(no % 10) + sumDigits(int(no / 10))
MOD = 1000000007
PMOD = 998244353
N = 10 ** 5
T = 1
T = int(stdin.readline())
for _ in range(T):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().rstrip().split()))
	v = []
	v.append(a[0])
	for i in range(1, n - 1):
		if a[i] <= a[i - 1] and a[i] < a[i + 1]:
			v.append(a[i])
		elif a[i] > a[i - 1] and a[i] > a[i + 1]:
			v.append(a[i])
	v.append(a[-1])
	ans = 0
	for i in range(len(v) - 1):
		if v[i] > v[i + 1]:
			ans += v[i] - v[i + 1]
	print(ans)


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from collections import Counter
inp = lambda : int(input())
strng = lambda : input().strip()
jn = lambda x, l: x.join(map(str, l))
strl = lambda : list(input().strip())
mul = lambda : map(int, input().strip().split())
mulf = lambda : map(float, input().strip().split())
seq = lambda : list(map(int, input().strip().split()))
ceil = lambda x: int(x) if x == int(x) else int(x) + 1
ceildiv = lambda x, d: x // d if x % d == 0 else x // d + 1
flush = lambda : stdout.flush()
stdstr = lambda : stdin.readline()
stdint = lambda : int(stdin.readline())
stdpr = lambda x: stdout.write(str(x))
stdarr = lambda : map(int, stdstr().split())
mod = 1000000007
for _ in range(stdint()):
	n = stdint()
	arr = list(stdarr())
	res = 0
	for i in range(1, n):
		if arr[i] < arr[i - 1]:
			res += arr[i - 1] - arr[i]
		else:
			continue
	print(res)


t = int(input())
for _ in range(t):
	n = int(input())
	li = list(map(int, input().split()))
	c = 0
	l = []
	x = li[0]
	for i in range(1, n):
		if li[i] < x:
			c += x - li[i]
		x = li[i]
	print(c)


t = int(input())
for _ in range(t):
	n = int(input())
	x = list(map(int, input().split()))
	res = []
	for i in range(1, len(x)):
		if x[i] < x[i - 1]:
			res.append(x[i - 1] - x[i])
		else:
			res.append(0)
	print(sum(res))


t = int(input())
for _ in range(t):
	n = int(input())
	A = list(map(int, list(input().split())))
	res = 0
	for i in range(1, n):
		res += max(0, A[i - 1] - A[i])
	print(res)


import sys, math
try:
	(sys.stdin, sys.stdout) = (open('input.txt', 'r'), open('out.txt', 'w'))
except:
	pass
from time import clock
a = clock()
from sys import stdin, stdout
mod = int(1000000000.0 + 7)
from statistics import mode
from collections import *
from math import ceil, floor, inf, factorial, gcd, log2, sqrt, log
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()

def lcm(a, b):
	return a * b // gcd(a, b)

def setbits(n):
	return bin(n).count('1')

def resetbits(n):
	return bin(n).count('0')

def modinv(n, p):
	return pow(n, p - 2, p)

def ncr(n, r):
	(num, den) = (1, 1)
	r = min(n, n - r)
	for i in range(r):
		num *= n - i
		den *= i + 1
	return num // den

def ncr_p(n, r, p):
	(num, den) = (1, 1)
	r = min(r, n - r)
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * modinv(den, p) % p

def isPrime(num):
	if num <= 1:
		return False
	if num == 2 or n == 3:
		return True
	if num % 2 == 0 or num % 3 == 0:
		return False
	m = int(num ** 0.5) + 1
	for i in range(5, m, 6):
		if num % i == 0 or num % (i + 2) == 0:
			return False
	return True

def bin_search(arr, low, high, val):
	while low <= high:
		mid = low + (high - low) // 2
		if arr[mid] == val:
			return mid
		elif arr[mid] < val:
			low = mid + 1
		else:
			high = mid - 1
	return -1

def sumofdigit(num):
	count = 0
	while num:
		count += num % 10
		num //= 10
	return count

def inputmatrix():
	(r, c) = iia()
	mat = [0] * r
	for i in range(r):
		mat[i] = iia()
	return (r, c, mat)

def prefix_sum(n, arr):
	for i in range(1, n):
		arr[i] += arr[i - 1]
	return arr

def binomial(n, k):
	if 0 <= k <= n:
		ntok = 1
		ktok = 1
		for t in range(1, min(k, n - k) + 1):
			ntok *= n
			ktok *= t
			n -= 1
		return ntok // ktok
	else:
		return 0

def divisors(n):
	res = []
	for i in range(1, ceil(sqrt(n)) + 1):
		if n % i == 0:
			if i == n // i:
				res.append(i)
			else:
				res.append(i)
				res.append(n // i)
	return res
for _ in range(ii1()):
	n = ii1()
	arr = iia()
	dic = [0]
	i = 0
	for i in range(1, n):
		if arr[i] >= arr[i - 1]:
			dic.append(0)
		else:
			dic.append(abs(arr[i] - arr[i - 1]))
	ans = 0
	i = 0
	s = 0
	while i < n:
		if dic[i] == 0:
			i += 1
		else:
			a = -inf
			while i < n and dic[i] != 0:
				a = max(a, dic[i])
				s += dic[i]
				i += 1
			ans += s
			a = -inf
			s = 0
	print(ans)


import sys
MOD = 10 ** 9 + 7

def power(a, b):
	if b == 0:
		return 1
	if b == 1:
		return a % MOD
	if b % 2 == 1:
		return power(a, b - 1) * a % MOD
	x = power(a, b / 2)
	return x * x % MOD
t = int(input())
while t > 0:
	n = int(input())
	a = [int(x) for x in input().split()]
	c = 0
	for i in range(n - 1):
		if a[i] > a[i + 1]:
			c += abs(a[i] - a[i + 1])
	print(c)
	t -= 1


import os
import sys
from io import BytesIO, IOBase
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')

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, defaultdict as dd
MOD = int(1000000000.0 + 7)
from copy import deepcopy

def main():
	for t in range(int(input())):
		n = int(input())
		l = [int(j) for j in input().split()]
		ans = 0
		for i in range(n - 1):
			if l[i + 1] < l[i]:
				ans += l[i] - l[i + 1]
		print(ans)
main()


T = int(input())
for case in range(T):
	i = int(input())
	ls = [int(x) for x in input().split()]
	m = 0
	stack = []
	idx = -1
	ret = []
	r = 0
	reuse = 0
	for i in ls:
		if i >= m:
			m = i
			reuse = 0
		else:
			if reuse <= m - i:
				r += m - i - reuse
			reuse = m - i
		m = max(m, i)
	print(r)


from sys import stdin, stdout
from collections import Counter
from collections import defaultdict
from math import ceil
from bisect import bisect_left
from bisect import bisect_right
import math
ai = lambda : list(map(int, stdin.readline().split()))
ei = lambda : map(int, stdin.readline().split())
ip = lambda : int(stdin.readline().strip())
for i in range(ip()):
	n = ip()
	li = ai()
	extra = [0] * n
	for i in range(n - 1):
		li[i] -= li[i + 1]
	ans = 0
	for i in range(n - 1):
		if li[i] > 0:
			ans += li[i]
	print(ans)


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


from functools import lru_cache
import sys
import math
mod = 10 ** 9 + 7
inf = float('inf')

def arrInt():
	return list(map(int, input().split()))
if 1 == 2:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	input = sys.stdin.readline
T = int(input())
for _ in range(T):
	n = int(input())
	arr = arrInt()
	print(sum([max(arr[i] - arr[i + 1], 0) for i in range(n - 1)]))


T = int(input())
for _ in range(T):
	N = int(input())
	a = [int(x) for x in input().split()]
	ans = 0
	for i in range(N - 1, 0, -1):
		(b, c) = (a[i], a[i - 1])
		if b < c:
			ans += c - b
	print(ans)


for j in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ct = 0
	i = len(l) - 1
	while i != 0:
		if l[i - 1] > l[i]:
			ct += l[i - 1] - l[i]
		i -= 1
	print(ct)


from collections import Counter
for _ in range(int(input())):
	input()
	array = [int(i) for i in input().split()]
	ans = 0
	prev = array[-1]
	for i in array[::-1]:
		if i > prev:
			ans += i - prev
		prev = i
	print(ans)


T = int(input())
for t in range(T):
	n = int(input())
	xs = [int(x) for x in input().split()]
	ans = 0
	for i in reversed(range(1, n)):
		if xs[i - 1] > xs[i]:
			ans += xs[i - 1] - xs[i]
	print(ans)


def solve(N, A):
	cnt = 0
	for i in range(N - 1):
		if A[i] > A[i + 1]:
			cnt += A[i] - A[i + 1]
	print(cnt)
t = int(input())
while t != 0:
	n = int(input())
	a = list(map(int, input().split(' ')))
	solve(n, a)
	t -= 1


t = int(input())
for qw in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	c = 0
	i = 1
	j = 0
	while i < n:
		if a[i] >= a[i - 1]:
			start = i
			i += 1
		else:
			j = i + 1
			mini = a[i]
			c += a[i - 1] - mini
			while j < n:
				if a[j] >= a[j - 1]:
					j += 1
				else:
					break
			i = j
	print(c)


n = int(input())
for i in range(n):
	lena = int(input())
	arr = list(map(int, input().split()))
	arr += [pow(10, 9) + 1]
	maxx = diff = final = 0
	for j in range(lena):
		final += max(arr[j] - arr[j + 1], 0)
	print(final)


n = int(input())
for i in range(n):
	k = int(input())
	l = list(map(int, input().split()))
	summ = 0
	for j in range(1, k):
		if l[j] < l[j - 1]:
			summ += l[j - 1] - l[j]
	print(summ)


import os
import sys
from io import BytesIO, IOBase
import math

def main():
	pass
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')
import os
import sys
from io import BytesIO, IOBase

def main():
	pass
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')
for xyz in range(0, int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = 0
	for i in range(1, n):
		if l[i] < l[i - 1]:
			ans += l[i - 1] - l[i]
	print(ans)


import math
for _ in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	i = n - 1
	ans = 0
	while i > 0:
		if A[i - 1] > A[i]:
			ans += A[i - 1] - A[i]
		i -= 1
	print(ans)


import os, sys
from collections import defaultdict, Counter, deque
from io import BytesIO, IOBase
from math import gcd

def lcm(x, y):
	return x * y // gcd(x, y)

def main():
	for i in range(int(input())):
		n = int(input())
		m = 0
		an = 0
		a = [int(c) for c in input().split()]
		for j in range(1, n):
			if a[j] < a[j - 1]:
				an += a[j - 1] - a[j]
		print(an)
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')
main()


n = int(input())
for i in range(n):
	t = int(input())
	arr = [int(item) for item in input().split()]
	count = 0
	for j in range(t - 2, -1, -1):
		if arr[j] > arr[j + 1]:
			count = count + arr[j] - arr[j + 1]
	print(count)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	res = 0
	last = 0
	for i in range(n):
		if a[i] < last:
			res += -a[i] + last
		last = a[i]
	print(res)


def solve(nums, n):
	if not nums:
		return 0
	stack = []
	ans = 0
	for num in nums:
		if stack and stack[-1] <= num:
			min_v = stack[-1]
			max_v = stack[-1]
			while stack and stack[-1] <= num:
				max_v = stack.pop()
			if stack:
				max_v = num
			ans += max_v - min_v
		stack.append(num)
	if stack:
		min_v = stack[-1]
		max_v = stack[0]
		ans += max_v - min_v
	return ans
for _ in range(int(input())):
	n = int(input())
	nums = list(map(int, input().split()))
	print(solve(nums, n))


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split())) + [10 ** 9 + 1]
	k = a[0]
	(ans, t) = (0, 0)
	for i in range(1, n):
		if a[i] >= k or a[i - 1] < a[i] > a[i + 1]:
			k = a[i]
			ans += t
			t = 0
		t = max(k - a[i], t)
	print(ans + t)


for i in range(int(input())):
	a = int(input())
	b = list(map(int, input().split()))
	c = 0
	for j in range(1, a):
		if b[j - 1] > b[j]:
			c += abs(b[j - 1] - b[j])
	print(c)


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	ops = 0
	for i in range(1, len(a)):
		if a[i] < a[i - 1]:
			ops += a[i - 1] - a[i]
	print(ops)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	lis = [0]
	for i in range(1, n):
		if l[i - 1] - l[i] > 0:
			lis.append(l[i - 1] - l[i])
		else:
			lis.append(0)
	print(sum(lis))


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


t = int(input())
while t:
	n = int(input())
	a = list(map(int, input().split(' ')))
	cnt = 0
	for i in range(1, len(a)):
		x = a[i - 1] - a[i] - cnt
		if x <= 0:
			a[i] = a[i] + cnt
			continue
		cnt += x
		a[i] = a[i] + cnt
	print(cnt)
	t = t - 1


from sys import stdin, stdout
from collections import Counter, OrderedDict
import math
cin = stdin.readline
cout = stdout.write
mp = lambda : list(map(int, cin().split()))

def chars():
	s = cin()
	return list(s[:len(s) - 1])

def pl(a):
	for val in a:
		cout(str(val) + ' ')
	cout('\n')
(t,) = mp()
for _ in range(t):
	(n,) = mp()
	a = mp()
	summ = 0
	for i in range(n - 1):
		summ += max(a[i] - a[i + 1], 0)
	pl([summ])


import sys
input = sys.stdin.readline
ins = lambda : input().rstrip()
ini = lambda : int(input().rstrip())
inm = lambda : map(int, input().split())
inl = lambda : list(map(int, input().split()))
ans = []
t = ini()
for _ in range(t):
	n = ini()
	a = inl()
	out = 0
	prev = 0
	count = 0
	for i in range(n):
		count += max(0, prev - a[i])
		prev = a[i]
	ans.append(count)
print('\n'.join(map(str, ans)))


t = int(input())
for q in range(t):
	n = int(input())
	arr = input().split()
	arr = [int(arr[i]) for i in range(n)]
	ans = 0
	for i in range(n - 1):
		if arr[i] > arr[i + 1]:
			ans += arr[i] - arr[i + 1]
	print(ans)


T = int(input())
for _ in range(T):
	N = int(input())
	A = [int(a) for a in input().split()]
	print(sum([max(A[i] - A[i + 1], 0) for i in range(N - 1)]))


t = int(input())
for q in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	moves = 0
	for i in range(1, n):
		if arr[i - 1] - arr[i] > 0:
			moves += arr[i - 1] - arr[i]
	print(moves)


T = int(input())
for t in range(T):
	n = int(input())
	q = input().split(' ')
	q = [int(x) for x in q]
	s = 0
	for i in range(1, n):
		if q[i] < q[i - 1]:
			s += q[i - 1] - q[i]
	print(s)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
from decimal import Decimal
mod = pow(10, 9) + 7
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(var, end='\n'):
	sys.stdout.write(str(var) + end)

def outa(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
for _ in range(int(data())):
	n = int(data())
	arr = l()
	answer = 0
	for i in range(n - 2, -1, -1):
		if arr[i] <= arr[i + 1]:
			continue
		answer += arr[i] - arr[i + 1]
		arr[i + 1] = arr[i]
	out(answer)


for _ in range(int(input())):
	z = input()
	ans = 0
	a = [int(i) for i in input().split()]
	for i in range(len(a) - 1):
		if a[i] > a[i + 1]:
			ans += abs(a[i] - a[i + 1])
	print(ans)


testCases = int(input())
heights = []
for i in range(testCases):
	input()
	heights.append(list(map(int, input().split(' '))))
for x in heights:
	ans = 0
	for i in range(len(x) - 1):
		ans += max(0, x[i] - x[i + 1])
	print(ans)


for _ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	ans = 0
	for i in range(n - 1):
		ans += -min(0, ar[i + 1] - ar[i])
	print(ans)


x = int(input())
for i in range(0, x):
	n = int(input())
	m = list(map(int, input().split()))[:n]
	m.reverse()
	s = 0
	for j in range(0, n - 1):
		if m[j] < m[j + 1]:
			s = s + m[j + 1] - m[j]
	print(s)


import sys
t = int(input())
answers = []
for i in range(t):
	n = int(input())
	a = [int(j) for j in input().split()]
	o = 0
	for i in range(n - 1):
		o += max(0, a[i] - a[i + 1])
	print(o)


t = int(input())
c = []
for i in range(t):
	n = int(input())
	a = [int(u) for u in input().split()]
	p = 0
	for i in range(n - 1):
		if a[i] > a[i + 1]:
			p += a[i] - a[i + 1]
	c.append(p)
for k in c:
	print(k)


import sys
sys.setrecursionlimit(10 ** 5)
input = lambda : sys.stdin.readline()[:-1]

def main():
	t = int(input())
	for case in range(t):
		n = int(input())
		A = list(reversed([int(x) for x in input().split()]))
		operations = 0
		prior = A[0]
		for pos in range(1, n):
			if prior < A[pos]:
				operations += A[pos] - prior
			prior = A[pos]
		print(operations)
	return
main()


t = int(input())
for ex in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	m = a[n - 1]
	ans = 0
	for i in range(n - 2, -1, -1):
		m = min(m, a[i])
		if a[i] >= a[i + 1]:
			ans += a[i] - m
			m = a[i]
	print(ans)


from sys import stdin
for _ in range(int(input())):
	n = int(stdin.readline())
	l = list(map(int, stdin.readline().rstrip().split(' ')))
	r = 0
	for i in range(n - 1):
		r += max(0, l[i] - l[i + 1])
	print(r)


import sys
import math
import heapq
import collections
fast_reader = sys.stdin.readline
fast_writer = sys.stdout.write

def input():
	return fast_reader().strip()

def print(*argv):
	fast_writer(' '.join((str(i) for i in argv)))
	fast_writer('\n')

def printspace(*argv):
	fast_writer(' '.join((str(i) for i in argv)))
	fast_writer(' ')

def inputnum():
	return int(input())

def inputnums():
	return map(int, input().split())

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

def inputstring():
	return [x for x in input()]

def inputmatrixchar(rows):
	arr2d = [[j for j in input().strip()] for i in range(rows)]
	return arr2d

def inputmatrixint(rows):
	arr2d = []
	for _ in range(rows):
		arr2d.append([int(i) for i in input().split()])
	return arr2d
t = int(input())
for q in range(t):
	n = inputnum()
	a = inputlist()
	ans = 0
	for i in range(1, n):
		if a[i] < a[i - 1]:
			ans += a[i - 1] - a[i]
	print(ans)


for t in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	count = 0
	if n == 1:
		print(0)
		continue
	for i in range(1, n):
		ele = arr[i] + count
		ele_prev = arr[i - 1] + count
		if ele >= ele_prev:
			continue
		else:
			count += ele_prev - ele
	print(count)


for _ in range(int(input())):
	n = int(input())
	a = [*map(int, input().split())]
	b = [a[i] - a[i - 1] for i in range(1, n)]
	print(sum((max(-i, 0) for i in b)))


t = int(input())
for test in range(0, t):
	n = int(input())
	heights = list(map(int, input().split(' ')))
	print(sum((max(0, heights[i] - heights[i + 1]) for i in range(0, n - 1))))


import sys
input = lambda : sys.stdin.readline().rstrip()
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	ans = 0
	for i in range(1, n):
		ans += max(0, a[i - 1] - a[i])
	print(ans)


t = int(input())
for _ in range(t):
	N = int(input())
	lst = list(map(int, input().split()))
	count = 0
	for i in range(1, N):
		count += max(0, lst[i - 1] - lst[i])
	print(count)


from sys import exit, stdin, stderr

def rl():
	return [int(w) for w in stdin.readline().split()]
(T,) = rl()
for _ in range(T):
	(n,) = rl()
	a = rl()
	r = 0
	for i in range(n - 1):
		d = a[i] - a[i + 1]
		if d > 0:
			r += d
	print(r)


t = int(input())
for i in range(0, t):
	m = int(input())
	arr = list(map(int, input().strip().split()))[:m]
	big = 0
	for j in range(0, m - 1):
		y = max(arr[j] - arr[j + 1], 0)
		big = big + y
	print(big)


t = int(input())
for r in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	s = 0
	for i in range(n - 1, 0, -1):
		if a[i] < a[i - 1]:
			s += a[i - 1] - a[i]
	print(s)


import math
import sys
import bisect
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	maxi = l[0]
	cost = 0
	cnt = 0
	for i in range(n - 1):
		cost += max(0, l[i] - l[i + 1])
	print(cost)


t = int(input())
for i in range(t):
	n = int(input())
	lis = list(map(int, input().split()))
	sumo = 0
	for j in range(len(lis) - 1, 0, -1):
		if lis[j] < lis[j - 1]:
			sumo = sumo + (lis[j - 1] - lis[j])
	print(sumo)


t = int(input())
for _ in range(t):
	res = 0
	n = int(input())
	arr = list(map(int, input().split()))
	if arr == sorted(arr):
		print(0)
		continue
	else:
		for i in range(1, n):
			if arr[i - 1] > arr[i]:
				res += arr[i - 1] - arr[i]
	print(res)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	dp = [0 for __ in range(n)]
	for i in range(1, n):
		if a[i - 1] - a[i] >= 0:
			dp[i] = dp[i - 1] + (a[i - 1] - a[i])
		else:
			dp[i] = dp[i - 1]
	print(dp[-1])


T = int(input())
while T:
	n = int(input())
	A = list(map(int, input().split()))
	x = 0
	for i in range(n - 1):
		x += max(0, A[i] - A[i + 1])
	print(x)
	T = T - 1


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	dp = [0] * n
	for i in range(1, n):
		if arr[i] < arr[i - 1]:
			dp[i] = dp[i - 1] + arr[i - 1] - arr[i]
	ans = 0
	i = 0
	while i < n:
		j = i
		if dp[i] != 0:
			while j < n and dp[j] > 0:
				j += 1
			ans += max(dp[i:j + 1])
		if i != j:
			i = j
		else:
			i += 1
	print(ans)


import sys
input = sys.stdin.readline
(inp, ip) = (lambda : int(input()), lambda : [int(w) for w in input().split()])
for _ in range(inp()):
	n = inp()
	x = ip()
	x = x[::-1]
	i = 0
	ans = 0
	while i < n:
		while i < n - 1 and x[i] >= x[i + 1]:
			i += 1
		if i >= n - 1:
			break
		ans += x[i + 1] - x[i]
		i += 1
	print(ans)


def fast1(arr):
	tups = []
	window = []
	arrMax = float('-inf')
	for num in arr:
		arrMax = max(arrMax, num)
		if len(window) == 0:
			window.append(num)
		elif num < window[-1]:
			tups.append([window[0], window[-1]])
			window = [num]
		else:
			window.append(num)
	if len(window) != 0:
		tups.append([window[0], window[-1]])
	beforeTups = []
	afterTups = []
	for i in range(len(tups)):
		if tups[i][1] == arrMax:
			beforeTups = tups[:i + 1]
			afterTups = tups[i + 1:]
			break
	result = 0
	for i in range(1, len(beforeTups)):
		(prevMin, prevMax) = beforeTups[i - 1]
		(currMin, currMax) = beforeTups[i]
		if prevMax > currMax:
			beforeTups[i] = [prevMax, prevMax]
		else:
			beforeTups[i] = [prevMax, currMax]
		result += prevMax - currMin
	afterTups.sort()
	for i in range(1, len(afterTups)):
		(prevMin, prevMax) = afterTups[i - 1]
		(currMin, currMax) = afterTups[i]
		result += currMin - prevMin
	if len(afterTups) > 0:
		result += arrMax - afterTups[-1][0]
	return result

def fast(arr):
	result = 0
	maxSeen = float('-inf')
	for (i, num) in enumerate(arr):
		if num >= maxSeen:
			maxSeen = num
		elif i > 0 and arr[i - 1] > arr[i]:
			result += arr[i - 1] - num
	return result

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		arr = list(map(int, input().split()))
		result = fast(arr)
		print(result)

def test():
	arr = [1, 6, 7, 9, 8, 7, 4, 10, 11, 12]
	f = fast(arr)
	print(f)
main()


t = int(input())
for o in range(t):
	n = int(input())
	l = list(map(int, input().strip().split()))
	ans = 0
	for i in range(n - 2, -1, -1):
		if l[i] > l[i + 1]:
			ans += l[i] - l[i + 1]
	print(ans)


def solve(n, A):
	ans = 0
	for i in range(n - 1):
		ans += max(0, A[i] - A[i + 1])
	return ans
t = int(input())
while t:
	res = []
	n = int(input())
	in_ = map(int, input().split(' '))
	for x in in_:
		res.append(int(x))
	print(solve(n, res))
	t -= 1


T = int(input())
for _ in range(T):
	n = int(input())
	l = list(map(int, input().split()))
	ans = 0
	for i in range(n - 1, 0, -1):
		if l[i] < l[i - 1]:
			ans += l[i - 1] - l[i]
	print(ans)


tt = int(input())
while tt:
	tt -= 1
	import math
	n = int(input())
	ll = list(map(int, input().split()))
	a = 0
	for i in range(0, n - 1):
		a += max(0, ll[i] - ll[i + 1])
	print(a)


import bisect
import decimal
from decimal import Decimal
import os
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
decimal.getcontext().prec = 46

def primeFactors(n):
	prime = set()
	while n % 2 == 0:
		prime.add(2)
		n = n // 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			prime.add(i)
			n = n // i
	if n > 2:
		prime.add(n)
	return list(prime)

def getFactors(n):
	factors = []
	i = 1
	while i <= math.sqrt(n):
		if n % i == 0:
			if n // i == i:
				factors.append(i)
			else:
				factors.append(i)
				factors.append(n // i)
		i = i + 1
	return factors

def modefiedSieve():
	mx = 10 ** 7 + 1
	sieve = [-1] * mx
	for i in range(2, mx):
		if sieve[i] == -1:
			sieve[i] = i
			for j in range(i * i, mx, i):
				if sieve[j] == -1:
					sieve[j] = i
	return sieve

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	num = []
	for p in range(2, n + 1):
		if prime[p]:
			num.append(p)
	return num

def lcm(a, b):
	return a * b // math.gcd(a, b)

def sort_dict(key_value):
	return sorted(key_value.items(), key=lambda kv: (kv[1], kv[0]))

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

def num_input():
	return map(int, input().split())

def string_list():
	return list(input())

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def binaryToDecimal(n):
	return int(n, 2)

def DFS(n, s, adj):
	visited = [False for i in range(n + 1)]
	stack = []
	stack.append(s)
	while len(stack):
		s = stack[-1]
		stack.pop()
		if not visited[s]:
			visited[s] = True
		for node in adj[s]:
			if not visited[node]:
				stack.append(node)

def maxSubArraySum(a, size):
	maxint = 10 ** 10
	max_so_far = -maxint - 1
	max_ending_here = 0
	for i in range(0, size):
		max_ending_here = max_ending_here + a[i]
		if max_so_far < max_ending_here:
			max_so_far = max_ending_here
		if max_ending_here < 0:
			max_ending_here = 0
	return max_so_far

def solve():
	n = int(input())
	arr = list_input()
	ans = 0
	for i in range(1, n):
		ans += max(0, arr[i - 1] - arr[i])
	print(ans)
t = 1
t = int(input())
for _ in range(t):
	solve()


import sys
input = sys.stdin.readline
t = int(input())
for t1 in range(t):
	n = int(input())
	l = list(map(int, input().split(' ')))
	ans = 0
	for i in range(1, n):
		if l[i] < l[i - 1]:
			ans += l[i - 1] - l[i]
	print(ans)


for _ in range(int(input())):
	input()
	r = 0
	m = 0
	for i in map(int, input().split()):
		r += max(0, m - i)
		m = i
	print(r)


t = int(input())
for p in range(t):
	n = int(input())
	ara = list(map(int, input().strip().split()))
	ans = 0
	for i in range(n - 1):
		ans += max(0, ara[i] - ara[i + 1])
	print(ans)


def modinv(n, p):
	return pow(n, p - 2, p)

def main():
	for case in range(int(input())):
		n = int(input())
		a = [int(x) for x in input().split()]
		left = a[0]
		d = 0
		ans = 0
		prev = a[0]
		for i in range(1, n):
			if a[i] < a[i - 1]:
				d += a[i - 1] - a[i]
			else:
				y = min(prev, a[i])
				inc = y - a[i - 1]
				ans += inc
				d -= inc
				prev = a[i]
		ans += d
		print(ans)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			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')
main()


for _ in range(int(input())):
	n = int(input())
	mx = 0
	num = list(map(int, input().split()))
	for i in range(len(num) - 1):
		mx += max(num[i] - num[i + 1], 0)
	print(mx)


T = int(input())
for t in range(T):
	n = int(input())
	l = [int(k) for k in input().split()]
	c = 0
	for i in range(1, n):
		if l[i] < l[i - 1]:
			c += l[i - 1] - l[i]
	print(c)


def solve(n, arr):
	ans = 0
	for i in range(n - 1):
		ans += max(arr[i] - arr[i + 1], 0)
	return ans
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split(' ')))
	print(solve(n, arr))


def solve(n, ar):
	comp = ar[0]
	dp = [0] * n
	dp[0] = 0
	for i in range(1, n):
		if ar[i] >= comp:
			comp = ar[i]
			dp[i] = dp[i - 1]
		elif ar[i] < ar[i - 1]:
			dp[i] = dp[i - 1] + ar[i - 1] - ar[i]
		else:
			dp[i] = dp[i - 1]
	print(dp[n - 1])
t = int(input())
for _ in range(t):
	n = int(input())
	ar = list(map(int, input().split()))
	solve(n, ar)


import collections

def solve(lst, k):
	minVal = 0
	mx = 0
	min_ = max(lst)
	k = max(lst)
	sw = False
	for i in range(len(lst) - 1, 0, -1):
		min_ = min(lst[i], min_)
		if lst[i] < lst[i - 1]:
			minVal += lst[i - 1] - min_
			min_ = k
	if minVal <= 0:
		return 0
	return minVal

def sort(key):
	return key[0]
ans = []
n = int(input())
for i in range(n):
	k = int(input())
	lst = list(map(int, input().split()))
	ans.append(solve(lst, k))
for i in ans:
	print(i)


from collections import deque
import sys
input = sys.stdin.readline
from sys import stdin, stdout

def main():
	for _ in range(int(input())):
		n = int(input())
		l = [int(s) for s in input().split()]
		s = deque([l[0]])
		c = 1
		ans = 0
		i = 1
		while i < n:
			if l[i] >= s[-1]:
				if c == 1:
					s.pop()
					s.append(l[i])
					i += 1
				elif s[-2] > l[i]:
					ans += l[i] - s[-1]
					s[-1] = s[-1] + l[i] - s[-1]
					i += 1
				else:
					ans += s[-2] - s[-1]
					s.pop()
					c -= 1
			else:
				s.append(l[i])
				c += 1
				i += 1
		while c > 1:
			w = s.pop()
			c -= 1
			ans += s[-1] - w
		print(ans)
main()


import sys
from math import sqrt
from collections import OrderedDict
inpt = sys.stdin.readline

def inp():
	return int(inpt())

def inlist():
	return list(map(int, inpt().split()))

def instr():
	s = inpt()
	return list(s[:len(s) - 1])

def invr():
	return map(int, inpt().split())

class node(object):

	def __init__(self, x, p, h):
		(self.x, self.p, self.h) = (x, p, h)
		self.children = []

	def add_child(self, obj):
		self.children.append(obj)

def main():
	t = inp()
	for l in range(t):
		n = inp()
		a = inlist()
		ans = 0
		for i in range(1, n):
			if a[i] < a[i - 1]:
				ans += a[i - 1] - a[i]
		print(ans)
main()


t = int(input())
for case in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	tot = 0
	for i in range(1, n):
		if arr[i] < arr[i - 1]:
			tot += arr[i - 1] - arr[i]
	print(tot)


import sys
In = sys.stdin.readline
t = int(In())
for _ in range(t):
	n = int(In())
	out = 0
	l = list(map(int, In().split()))
	for i in range(n - 1):
		out += max(0, l[i] - l[i + 1])
	print(out)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	yes = 0
	now = a[0]
	ans = 0
	for i in range(1, n):
		if a[i] < a[i - 1] and yes == 0:
			now = a[i - 1]
			yes = 1
		elif a[i] >= a[i - 1] and yes == 1:
			ans += now - a[i - 1]
			yes = 0
	if yes == 1:
		ans += now - a[-1]
	print(ans)


for t in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()] + [-1]
	res = []
	flag = False
	for i in range(n):
		if not flag:
			minval = a[i]
			flag = True
		if a[i] <= a[i + 1]:
			continue
		else:
			maxval = a[i]
			flag = False
			res.append([minval, maxval])
	ans = 0
	for i in range(len(res) - 1):
		ans += res[i][1] - res[i + 1][0]
	print(ans)


from sys import stdin, stdout
from collections import Counter
from itertools import permutations
import bisect
import math
I = lambda : map(int, stdin.readline().split())
I1 = lambda : stdin.readline()
for _ in range(int(I1())):
	n = int(I1())
	a = list(I())
	Max = a[0]
	Min = a[0]
	(c, f) = (0, 0)
	for i in range(1, n):
		if a[i] >= a[i - 1]:
			c += Max - Min
			Max = Min = a[i]
		else:
			Max = max(a[i - 1], Max)
			Min = min(a[i], Min)
	c += Max - Min
	print(c)


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def fi():
	return float(input())

def si():
	return input()

def msi():
	return map(str, input().split())

def mi():
	return map(int, input().split())

def li():
	return list(mi())

def lsi():
	return list(msi())

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def lcm(x, y):
	return x * y // gcd(x, y)
mod = 1000000007

def ceil(x, y):
	if x % y == 0:
		return x // y
	else:
		return x // y + 1
from math import log, factorial, cos, tan, sin, radians, floor, sqrt, log2
import bisect
import random
import string
from decimal import *

def reverse(x):
	return x[::-1]

def main():
	n = ii()
	a = li()
	mx = 1000000007
	cn = 0
	for i in range(n - 1, -1, -1):
		if mx < a[i]:
			cn += a[i] - mx
			mx = a[i]
		mx = min(mx, a[i])
	print(cn)
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):
	(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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(ii()):
	main()


test = int(input())
for i in range(test):
	n = int(input())
	li = input().split()
	li = list(map(int, li))
	count = 0
	for i in range(1, n):
		pre = li[i] + count
		if pre < li[i - 1]:
			count += li[i - 1] - pre
			li[i] = li[i - 1]
			continue
		else:
			li[i] += count
	print(count)


from sys import stdin, stdout
from math import gcd, sqrt, factorial
from collections import deque, defaultdict
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(x)
lcm = lambda x, y: x * y // gcd(x, y)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 0 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 9 + 7
for _ in range(I()):
	n = I()
	a = L()
	mx = a[0]
	sm = 0
	h = 0
	for i in a[1:]:
		if i + h < mx:
			v = mx - (i + h)
			sm += v
			h += v
		mx = i + h
	print(sm)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	bar = 0
	ans = 0
	moves = [0 for i in range(n)]
	for i in range(n):
		if a[i] > bar:
			bar = a[i]
		elif a[i] < bar:
			if a[i] >= a[i - 1]:
				moves[i] = bar - a[i]
			else:
				ans += a[i - 1] - a[i]
				moves[i] = bar - a[i]
	print(ans)


for tc in range(int(input())):
	n = int(input())
	line = input().split()
	arr = []
	for i in range(n):
		arr.append(int(line[i]))
	count = 0
	for i in range(n - 1, 0, -1):
		if arr[i] < arr[i - 1]:
			count += arr[i - 1] - arr[i]
	print(count)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
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')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default='z', func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
for ik in range(int(input())):
	n = int(input())
	t = 0
	w = 0
	l = list(map(int, input().split()))
	target = [l[0]]
	for i in range(1, n):
		target.append(max(target[-1], l[i]))
	ans = 0
	for i in range(1, n):
		if t == 1:
			if l[i] < target[i]:
				w = target[i] - l[i]
				l[i] += cur
				l[i] = min(l[i], target[i])
				ans += target[i] - l[i]
				cur = w
			else:
				ans += target[i] - l[i]
				t = 0
		elif l[i] < target[i]:
			t = 1
			cur = target[i] - l[i]
			ans += cur
		else:
			t = 0
	print(ans)


import math
import os
import random
import re
import string
from sys import *
from collections import *

def bs(arr, x, l, r):
	if l <= r:
		mid = (r + l) // 2
		if arr[mid] == x:
			return mid
		elif arr[mid] > x:
			return bs(arr, x, l, mid - 1)
		else:
			return bs(arr, x, mid + 1, r)
	else:
		return -1

def solve():
	for _ in range(int(input())):
		n = int(input())
		l = list(map(int, stdin.readline().strip().split()))
		c = 0
		for i in range(n - 1):
			c += max(0, l[i] - l[i + 1])
		print(c)
solve()


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	c = 0
	p = l[0]
	for i in l:
		if i < p:
			c += p - i
		p = i
	print(c)


for _ in range(int(input())):
	n = int(input())
	l = [int(x) for x in input().split()]
	maxi = l[0]
	ans = 0
	for i in range(1, len(l)):
		if l[i] >= maxi:
			maxi = l[i]
			continue
		else:
			ans += maxi - l[i]
			maxi = l[i]
	print(ans)


Test = int(input())
while Test:
	Test -= 1
	n = int(input())
	arr = list(map(int, input().split()))[:n]
	C = 0
	I = 0
	J = 0
	while I < n:
		I += 1
		if I < n and arr[I - 1] > arr[I]:
			J = I
			while J < n and arr[J - 1] > arr[J] and (arr[J - 1] > arr[J]):
				J += 1
			C += arr[I - 1] - min(arr[I:J + 1])
		if J > I:
			I = J
	print(C)


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


def main():
	n = int(input())
	arr = list(map(int, input().split()))
	(ans, m) = (0, max(arr))
	cur = 0
	i = 0
	while i < n - 1:
		ans += max(0, arr[i] - arr[i + 1])
		i += 1
	print(ans)
for _ in range(int(input())):
	main()


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


import sys
import math
import itertools
import functools
import collections
import operator
import fileinput
import copy
ORDA = 97

def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return [int(i) for i in input().split()]

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)

def revn(n):
	return str(n)[::-1]

def dd():
	return collections.defaultdict(int)

def ddl():
	return collections.defaultdict(list)

def sieve(n):
	if n < 2:
		return list()
	prime = [True for _ in range(n + 1)]
	p = 3
	while p * p <= n:
		if prime[p]:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 2
	r = [2]
	for p in range(3, n + 1, 2):
		if prime[p]:
			r.append(p)
	return r

def divs(n, start=2):
	r = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				r.append(i)
			else:
				r.extend([i, n // i])
	return r

def divn(n, primes):
	divs_number = 1
	for i in primes:
		if n == 1:
			return divs_number
		t = 1
		while n % i == 0:
			t += 1
			n //= i
		divs_number *= t

def prime(n):
	if n == 2:
		return True
	if n % 2 == 0 or n <= 1:
		return False
	sqr = int(math.sqrt(n)) + 1
	for d in range(3, sqr, 2):
		if n % d == 0:
			return False
	return True

def convn(number, base):
	new_number = 0
	while number > 0:
		new_number += number % base
		number //= base
	return new_number

def cdiv(n, k):
	return n // k + (n % k != 0)

def ispal(s):
	for i in range(len(s) // 2 + 1):
		if s[i] != s[-i - 1]:
			return False
	return True
for _ in range(ii()):
	n = ii()
	a = li()
	ans = 0
	for i in range(n - 1):
		ans += max(0, a[i] - a[i + 1])
	print(ans)


for _ in range(int(input())):
	n = int(input())
	op = 0
	w = 0
	for i in map(int, input().split()):
		op += max(0, w - i)
		w = i
	print(op)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	t = 0
	mini = cur = a[0]
	for i in range(n - 1, 0, -1):
		t += max(a[i - 1] - a[i], 0)
	print(t)


t = int(input())
for _ in range(t):
	n = int(input())
	ar = list(map(int, input().split()))
	s = 0
	for i in range(n - 1, 0, -1):
		s += max(0, ar[i - 1] - ar[i])
	print(s)


t = int(input())
anss = []
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split(sep=' ')))
	ans = 0
	for i in range(len(l))[1:]:
		ans += max(0, l[i - 1] - l[i])
	anss.append(ans)
for i in anss:
	print(i)


def ii():
	return int(input())

def si():
	return input()

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

def mi():
	return map(int, input().split())
for _ in range(ii()):
	n = ii()
	arr = li()
	fin = [0] * n
	for i in range(n - 1):
		if arr[i] > arr[i + 1]:
			fin[i] = arr[i] - arr[i + 1]
	print(sum(fin))


t = int(input())
for _ in range(t):
	n = int(input())
	l1 = [int(x) for x in input().split()]
	ans = 0
	for i in range(n):
		if i == 0:
			old = l1[0]
		elif old > l1[i]:
			ans += old - l1[i]
			old = l1[i]
		else:
			old = l1[i]
	print(ans)


from sys import stdin

def inp():
	return stdin.buffer.readline().rstrip().decode('utf8')

def itg():
	return int(stdin.buffer.readline())

def mpint():
	return map(int, stdin.buffer.readline().split())
for case in range(1, itg() + 1):
	n = itg()
	arr = tuple(mpint())
	a = arr[-1]
	ans = 0
	for i in range(n - 2, -1, -1):
		if a < arr[i]:
			ans += arr[i] - a
		a = arr[i]
	print(ans)


from typing import List

def omkar_and_waterslide(nums: List[int]) -> int:
	ops = 0
	curr_supp_min = nums[-1]
	for num in reversed(nums):
		if curr_supp_min < num:
			ops += num - curr_supp_min
			curr_supp_min = num
		else:
			curr_supp_min = num
	return ops
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	print(omkar_and_waterslide(a))


t = int(input())
for test in range(0, t):
	n = int(input())
	heights = list(map(int, input().split(' ')))
	heights = [heights[0]] + heights + [heights[-1]]
	peak = None
	prev_height = heights[0]
	changes = 0
	for index in range(1, n + 1):
		cur_height = heights[index]
		if cur_height > prev_height and peak is not None:
			changes += peak - prev_height
			peak = None
		elif cur_height < prev_height and peak is None:
			peak = prev_height
		prev_height = cur_height
	if peak is not None:
		changes += peak - prev_height
	print(changes)


int_inp = lambda : int(input())
strng = lambda : input().strip()
strl = lambda : list(input().strip())
mul = lambda : map(int, input().strip().split())
mulf = lambda : map(float, input().strip().split())
seq = lambda : list(map(int, input().strip().split()))
import math
from collections import Counter, defaultdict
for _ in range(int_inp()):
	k = int_inp()
	m = seq()
	pre = -1
	j = 0
	l = 0
	for i in m:
		if i < pre:
			l += pre2 - i
		j += 1
		pre = i
		pre2 = max(pre, i)
	print(l)


for _ in range(int(input())):
	size = int(input())
	nums = [int(x) for x in input().split()]
	prev = 0
	for j in range(size - 1, 0, -1):
		prev += max(0, nums[j - 1] - nums[j])
	print(prev)


for i in range(int(input())):
	n = int(input())
	b = list(map(int, input().split()))
	sum = 0
	for i in range(len(b) - 1):
		if b[-2 - i] > b[-1 - i]:
			sum += b[-2 - i] - b[-1 - i]
	print(sum)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	mi = float('inf')
	ans = 0
	val = 0
	f = 0
	i = 1
	while i < n:
		if l[i] < l[i - 1]:
			val = l[i - 1]
			j = i
			mi = l[i]
			while j < n:
				if l[j] < val and l[j] >= l[j - 1]:
					mi = min(mi, l[j])
					j += 1
				else:
					break
			ans += val - mi
			i = j + 1
		else:
			i += 1
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	i = 1
	j = i
	ans = 0
	while i < n:
		j = i
		if l[i] < l[i - 1]:
			j = i
			mi = l[i]
			while j < n and l[j] < l[i]:
				if mi > l[j]:
					mi = l[j]
				j = j + 1
			ans = ans + l[i - 1] - mi
		i = j + 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l1 = []
	for i in range(1, n):
		l1.append(l[i] - l[i - 1])
	a = 0
	for p in l1:
		if p < 0:
			a += -p
	print(a)


from math import *
from collections import *
from functools import *
from bisect import *
from itertools import *
from heapq import *
from statistics import *
inf = float('inf')
ninf = -float('inf')
ip = input
alphal = 'abcdefghijklmnopqrstuvwxyz'
alphau = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

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

def ipn():
	return int(input())

def ipf():
	return float(input())

def solve():
	n = ipn()
	a = ipl()
	r = 0
	for i in range(n - 1):
		r += max(0, a[i] - a[i + 1])
	print(r)
for _ in range(ipn()):
	solve()


t = int(input())
for __ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	cost = 0
	for i in range(n - 1):
		l = arr[i]
		r = arr[i + 1]
		cost += max(l - r, 0)
	print(cost)


def incr(a, I):
	for i in range(I):
		if a[i] >= a[i + 1]:
			return False
	return True
T = int(input())
for _ in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	a = a + [1000000002] + [1000000001]
	maxx = max(a)
	ans = 0
	i = 0
	while i < n:
		if a[i] > a[i + 1]:
			for j in range(i, n + 1):
				if a[j] > a[j + 1] and a[i + 1:j + 1] != []:
					ans += a[i] - min(a[i + 1:j + 1])
					i = j - 1
					break
		i += 1
	print(ans)


testcases = int(input())
for testcase in range(testcases):
	n = int(input())
	temparr = input()
	temparr = temparr.split()
	arr = []
	for i in temparr:
		arr.append(int(i))
	ans = 0
	prev = arr[0]
	for i in range(1, n):
		cur = arr[i]
		if prev > cur:
			ans += prev - cur
		prev = cur
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	heights = list(map(int, input().split()))
	counter = 0
	operations = 0
	while counter <= n - 2:
		if heights[counter] > heights[counter + 1]:
			contiguous = []
			min_height = heights[counter]
			while counter <= n - 2:
				if heights[counter + 1] < heights[counter]:
					contiguous.append(heights[counter + 1])
					counter += 1
				else:
					break
			operations += min_height - min(contiguous)
		else:
			counter += 1
	print(operations)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	for i in range(n - 1):
		ans += max(0, a[n - i - 2] - a[n - i - 1])
	print(ans)


import sys
input = sys.stdin.buffer.readline
inin = lambda : int(input())
inar = lambda : list(map(int, input().split()))
inst = lambda : input().decode().rstrip('\n\r')
INF = float('inf')
_T_ = inin()
for _t_ in range(_T_):
	n = inin()
	a = inar()
	mtn = a[0]
	i = 1
	cnt = 0
	while i < n:
		if a[i] < mtn:
			mini = a[i]
			while i < n and a[i] < mtn:
				if a[i] < a[i - 1]:
					cnt += a[i - 1] - a[i]
				if a[i] > a[i - 1]:
					cnt += 0
				i += 1
		else:
			mtn = max(mtn, a[i])
			i += 1
	print(cnt)


t = int(input())

def kaput(i, a):
	for j in range(i, -len(a) - 1, -1):
		if a[i] >= a[j] and j != -len(a):
			i = j
		elif a[i] >= a[j] and j == -len(a):
			return 0
		else:
			return j
for k in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	s = 0
	index = -1
	while index != 0:
		index = kaput(index, a)
		if index != 0:
			s += a[index] - a[index + 1]
	print(s)


import sys
from collections import defaultdict
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	c = 0
	for i in range(1, n):
		if lis[i] < lis[i - 1]:
			c += lis[i - 1] - lis[i]
	print(c)


for i in range(int(input())):
	n = int(input())
	l = [int(x) for x in input().split()]
	c = 0
	for i in range(n - 1, 0, -1):
		if l[i] < l[i - 1]:
			c += l[i - 1] - l[i]
	print(c)


t = int(input())
while t:
	t -= 1
	n = int(input())
	arr = list(map(int, input().split()))
	if n == 1:
		print('0')
	else:
		ans = 0
		for i in range(1, n):
			ans += max(arr[i - 1] - arr[i], 0)
		print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	intervals = []
	start = a[0]
	for i in range(n - 1):
		if a[i] > a[i + 1]:
			intervals.append((start, a[i]))
			start = a[i + 1]
	intervals.append((start, a[-1]))
	ct = 0
	for i in range(len(intervals) - 1, 0, -1):
		ct += intervals[i - 1][1] - intervals[i][0]
	print(ct)


import sys
import math
from math import factorial, inf, gcd
from heapq import *
from functools import *
from itertools import *
from collections import *
from typing import *
sys.setrecursionlimit(10 ** 5)
t = int(input())
for ii in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	ans = 0
	for i in reversed(range(1, n)):
		if a[i] < a[i - 1]:
			ans += a[i - 1] - a[i]
	print(ans)


for i in ' ' * int(input()):
	input()
	(q, w) = (0, 0)
	for i in map(int, input().split()):
		q += max(0, w - i)
		w = i
	print(q)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	if a == sorted(a):
		print(0)
	else:
		moves = 0
		for i in range(n - 1, 0, -1):
			if a[i] < a[i - 1]:
				moves += a[i - 1] - a[i]
		print(moves)


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


import sys
input = sys.stdin.readline
inf = int(10000000000.0)
t = int(input())
for _ in range(t):
	n = int(input())
	lis = list(map(int, input().split()))
	maxx = lis[-1]
	ans = 0
	for i in range(n - 2, -1, -1):
		if lis[i] <= lis[i + 1]:
			continue
		d = lis[i] - lis[i + 1]
		ans += d
	print(ans)


t = int(input())
for k in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	op = 0
	for i in range(1, n):
		if a[i] < a[i - 1]:
			op += a[i - 1] - a[i]
	print(op)


import sys
import math

def get_array():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def input():
	return sys.stdin.readline().strip()
for _ in range(int(input())):
	n = int(input())
	a = get_array()
	ans = 0
	for i in range(n - 1):
		if a[i] > a[i + 1]:
			ans += a[i] - a[i + 1]
	print(ans)


t = int(input())
while t:
	n = int(input())
	nums = list(map(int, input().split()))
	difference = 0
	for i in range(n - 1):
		if nums[i] > nums[i + 1]:
			difference += nums[i] - nums[i + 1]
	print(difference)
	t -= 1


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


import os
import sys
from io import BytesIO, IOBase
from collections import Counter, defaultdict
from collections import deque
from functools import cmp_to_key
import math

def sin():
	return input()

def ain():
	return list(map(int, sin().split()))

def sain():
	return input().split()

def iin():
	return int(sin())
MAX = float('inf')
MIN = float('-inf')
MOD = 1000000007

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	s = set()
	for p in range(2, n + 1):
		if prime[p]:
			s.add(p)
	return s

def readTree(n, m):
	adj = [deque([]) for _ in range(n + 1)]
	for _ in range(m):
		(u, v) = ain()
		adj[u].append(v)
		adj[v].append(u)
	return adj

def main():
	for _ in range(iin()):
		n = iin()
		a = ain()
		ans = 0
		for i in range(n - 1):
			ans += max(0, a[i] - a[i + 1])
		print(ans)
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')
if os.getcwd() == 'D:\\code':
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def getNumber(n, arr):
	count = 0
	i = 1
	while i < n:
		if arr[i] < arr[i - 1]:
			count = count + (arr[i - 1] - arr[i])
		i += 1
	return count
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	print(getNumber(n, a))


n = int(input())
for q in range(n):
	x = int(input())
	arr = list(map(int, input().rstrip().split()))
	count = 0
	for i in range(1, x):
		if arr[i] < arr[i - 1]:
			count += arr[i - 1] - arr[i]
	print(count)


for _ in range(int(input())):
	n = int(input())
	val = list(map(int, input().strip().split()))
	p = 0
	ans = 0
	for i in val:
		if i < p:
			ans += p - i
		p = i
	print(ans, end='\n')


t = int(input())
while t > 0:
	n = int(input())
	a = [int(i) for i in input().split()]
	ans = 0
	for i in range(1, n):
		if a[i] >= a[i - 1]:
			continue
		else:
			ans += a[i - 1] - a[i]
	print(ans)
	t -= 1


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	t1 = max(a)
	c = 0
	for i in range(n - 1, 0, -1):
		if a[i] < a[i - 1]:
			c += a[i - 1] - a[i]
	print(c)


for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	m = [a[0]]
	for i in range(1, n):
		m.append(max(m[-1], a[i]))
	ans = 0
	for i in range(n - 1, 0, -1):
		if a[i] < a[i - 1]:
			ans += a[i - 1] - a[i]
	print(ans)


T = int(input())
for t in range(T):
	n = int(input())
	lista = list(map(int, input().strip().split()))
	sum = 0
	for i in range(n - 1):
		term = lista[i + 1] - lista[i]
		val = max(-term, 0)
		sum += val
	print(sum)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	li = []
	cnt = 0
	for j in range(n - 1):
		if a[j] > a[j + 1]:
			li.append(j)
	for j in range(len(li) - 1, -1, -1):
		if li[j] + 1 < n:
			cnt += a[li[j]] - a[li[j] + 1]
	print(cnt)


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


from sys import stdin, stdout
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	b = []
	cur = [a[0]]
	p = 1
	ans = 0
	while p < n + 1:
		if p == n:
			b += [cur]
		elif a[p] >= a[p - 1]:
			cur += [a[p]]
		else:
			b += [cur]
			cur = [a[p]]
		p += 1
	nn = len(b)
	mx = b[0][-1]
	for i in range(1, nn):
		cur = b[i]
		mx_now = 0
		for v in cur:
			if v < mx:
				mx_now = max(mx_now, v)
			else:
				break
		ans += mx_now - cur[0] + (mx - mx_now)
		mx = cur[-1]
	print(ans)


from __future__ import division, print_function
from sys import stdin, stdout
import bisect
import math
import heapq
i_m = 9223372036854775807

def inin():
	return int(input())

def stin():
	return input()

def spin():
	return map(int, stin().split())

def lin():
	return list(map(int, stin().split()))

def matrix(n):
	return [list(map(int, input().split())) for i in range(n)]

def count2Dmatrix(i, list):
	return sum((c.count(i) for c in list))

def modinv(n, p):
	return pow(n, p - 2, p)

def GCD(x, y):
	x = abs(x)
	y = abs(y)
	if min(x, y) == 0:
		return max(x, y)
	while y:
		(x, y) = (y, x % y)
	return x

def Divisors(n):
	l = []
	for i in range(1, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
	return l
prime = []

def SieveOfEratosthenes(n):
	global prime
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	f = []
	for p in range(2, n):
		if prime[p]:
			f.append(p)
	return f
q = []

def dfs(n, d, v, c):
	global q
	v[n] = 1
	x = d[n]
	q.append(n)
	j = c
	for i in x:
		if i not in v:
			f = dfs(i, d, v, c + 1)
			j = max(j, f)
	return j
for _ in range(inin()):
	n = inin()
	a = lin()
	d = []
	s = 0
	for i in range(n - 1):
		d.append(a[i + 1] - a[i])
		if a[i + 1] - a[i] < 0:
			s += a[i] - a[i + 1]
	print(s)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	steps = 0
	pos = n - 1
	while pos > 0:
		while pos > 0 and a[pos - 1] <= a[pos]:
			pos -= 1
		if pos == 0:
			break
		steps += a[pos - 1] - a[pos]
		pos -= 1
	print(steps)


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


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split(' ')))
	ans = []
	for i in range(n - 1):
		if arr[i + 1] >= arr[i]:
			pass
		else:
			ans.append(arr[i] - arr[i + 1])
	if ans:
		print(sum(ans))
	else:
		print(0)


def sol():
	x = int(input())
	s = list(map(int, input().split()))
	res = 0
	for n in range(x - 1, 0, -1):
		if s[n] < s[n - 1]:
			res += s[n - 1] - s[n]
	print(res)
for _ in range(int(input())):
	sol()


for _ in range(int(input())):
	a = int(input())
	b = list(map(int, input().split()))
	w = b[0]
	ans = 0
	for i in range(1, len(b)):
		if b[i] >= w:
			w = b[i]
		else:
			ans += w - b[i]
			w = b[i]
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split())) + [float('INF')]
	ans = 0
	now = 0
	d = 1
	m = 0
	for i in range(n + 1):
		if a[i] >= m:
			if d == 1:
				ans += m - now
			else:
				ans += m - now
				d = 1
		elif a[i] >= now:
			ans += a[i] - now
			d = 1
		else:
			now = a[i]
			d = -1
		now = a[i]
		m = max(m, now)
	print(ans)


import sys
from collections import defaultdict
t = 1
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, sys.stdin.readline().strip().split()))
	op = 0
	for j in range(1, n):
		if a[j] > a[j - 1]:
			continue
		else:
			op += a[j - 1] - a[j]
	print(op)


for _ in range(int(input())):
	n = int(input())
	A = list(map(int, input().split(' ')))
	count = 0
	for i in range(1, n):
		diff = A[i] - A[i - 1]
		if diff >= 0:
			continue
		else:
			count -= diff
	print(count)


for _ in range(int(input())):
	n = int(input())
	a = [0] + [*map(int, input().split())]
	d = [0] * (n + 1)
	for i in range(1, n + 1):
		d[i] = a[i] - a[i - 1]
	s = 0
	i = 1
	while i <= n:
		if d[i] >= 0:
			i += 1
			continue
		mn = d[i]
		while i + 1 <= n and d[i + 1] < 0:
			i += 1
			mn += d[i]
		s += -1 * mn
		i += 1
	print(s)


cases = int(input())
for i in range(cases):
	n = int(input())
	l2 = input().split(' ')
	arr = []
	for a in l2:
		arr.append(int(a))
	moves = 0
	for j in range(n - 1):
		ele1 = arr[j]
		ele2 = arr[j + 1]
		if ele1 > ele2:
			moves += ele1 - ele2
	print(moves)


from collections import deque
T = int(input())
for t in range(T):
	n = int(input())
	arr = list(map(int, input().split()))
	arr.reverse()
	q = deque()
	ans = 0
	for i in range(n):
		m = float('inf')
		while q and arr[i] >= q[-1]:
			tmp = q.pop()
			if tmp < m:
				m = tmp
				ans += arr[i] - tmp
		q.append(arr[i])
	print(ans)


import os
import heapq
import sys, threading
import math
import bisect
import operator
from collections import defaultdict
sys.setrecursionlimit(10 ** 5)
from io import BytesIO, IOBase

def gcd(a, b):
	if b == 0:
		return a
	else:
		return gcd(b, a % b)

def power(x, p, m):
	res = 1
	while p:
		if p & 1:
			res = res * x % m
		x = x * x % m
		p >>= 1
	return res

def inar():
	return [int(k) for k in input().split()]

def lcm(num1, num2):
	return num1 * num2 // gcd(num1, num2)

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		arr = inar()
		ans = 0
		stack = [arr[-1]]
		for i in range(n - 2, -1, -1):
			if arr[i] > stack[-1]:
				temp = 0
				while 1:
					if len(stack) == 0 or stack[-1] >= arr[i]:
						stack.append(arr[i])
						ans += temp
						break
					temp = max(temp, abs(arr[i] - stack[-1]))
					stack.pop()
			else:
				stack.append(arr[i])
		print(ans)
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')
main()


for s in [*open(0)][2::2]:
	(*s,) = map(int, s.split())
	print(sum(((a - b) * (a > b) for (a, b) in zip(s, s[1:]))))


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	x = int(input())
	l = list(map(int, input().split()))
	ans = 0
	tmp = 0
	last = l[0]
	for i in range(1, x):
		if l[i] < l[i - 1]:
			tmp = max(tmp, last - l[i])
		else:
			last = l[i]
			ans += tmp
			tmp = 0
	ans += tmp
	print(ans)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	ans = 0
	for i in range(1, n + 1):
		if i != n:
			if ar[-i - 1] > ar[-i]:
				ans += ar[-i - 1] - ar[-i]
	print(ans)


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


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


import sys
import math
from math import *
from collections import Counter, defaultdict

def main():
	n = int(input())
	arr = list(map(int, input().split()))
	mx = max(arr)
	idx = arr[::-1].index(mx)
	idx = n - idx - 1
	p = arr[-1]
	ans = mx - arr[-1]
	for i in range(n - 2, idx - 1, -1):
		if arr[i] < p:
			ans += p - arr[i]
		p = arr[i]
	i = idx - 1
	t = i
	while i > 0:
		if arr[i - 1] > arr[i]:
			ans += arr[i - 1] - arr[i]
		i -= 1
	print(ans)
for i in range(int(input())):
	main()


for _ in range(int(input())):
	sum = 0
	n = int(input())
	ls = list(map(int, input().split()))
	for i in range(n - 1):
		if ls[i] > ls[i + 1]:
			sum += abs(ls[i + 1] - ls[i])
	print(sum)


import math
t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	k = list(map(int, input().split()))
	count = 0
	for i in range(1, n):
		if k[i] < k[i - 1]:
			count += k[i - 1] - k[i]
	print(count)


for i in range(int(input())):
	n = int(input())
	ls = [int(a) for a in input().split()]
	st = 0
	for j in range(n - 1):
		if ls[j] > ls[j + 1]:
			st += ls[j] - ls[j + 1]
	print(st)


from sys import stdin, stdout
import math
from itertools import permutations, combinations
from collections import defaultdict
from bisect import bisect_left
from bisect import bisect_right

def L():
	return list(map(int, stdin.readline().split()))

def In():
	return map(int, stdin.readline().split())

def I():
	return int(stdin.readline())
P = 1000000007

def main():
	for t in range(I()):
		n = I()
		arr = L()
		ans = 0
		for i in range(n - 1):
			ans += max(arr[i] - arr[i + 1], 0)
		print(ans)
main()


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
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
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):
	(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))
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
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

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 zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		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

def solve():
	n = int(inp())
	a = lis()
	ans = 0
	for i in range(n - 1):
		ans += max(0, a[i] - a[i + 1])
	print(ans)
testcase(int(inp()))


t = int(input())
for _ in range(t):
	n = int(input())
	lis = list(map(int, input().split()))
	if n == 1:
		print(0)
	else:
		xxx = []
		for i in range(1, n):
			xxx.append(lis[i] - lis[i - 1])
		mn = min(xxx)
		if mn >= 0:
			print(0)
		else:
			sss = 0
			i = 0
			while i < len(xxx):
				if xxx[i] < 0:
					local = 0
					while i < len(xxx) and xxx[i] < 0:
						local += xxx[i]
						i += 1
					sss += local
				else:
					i += 1
			print(abs(sss))


MOD = 1000000007
from collections import defaultdict as dd, Counter, deque

def si():
	return input()

def ii():
	return int(input())

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

def mi():
	return map(int, input().split())

def out(v):
	print(v)

def spout():
	print(v, end=' ')

def d2b(n):
	return bin(n).replace('0b', '')

def twod(n, m, num):
	return [[num for x in range(m)] for y in range(n)]

def vow():
	return ['a', 'e', 'i', 'o', 'u']

def let():
	return [chr(i) for i in range(97, 123)]

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def ispow2(x):
	return x and (not x & x - 1)

def prime_factors(n):
	i = 2
	factors = []
	while i * i <= n:
		if n % i:
			i += 1
		else:
			n //= i
			factors.append(i)
	if n > 1:
		factors.append(n)
	return list(factors)
t = ii()
while t:
	t -= 1
	n = ii()
	a = li()
	ans = i = 0
	while i < n - 1:
		ans += max(0, a[i] - a[i + 1])
		i += 1
	print(ans)


import sys
t = int(input())
i = 0
for line in sys.stdin:
	if i == 0:
		n = int(line)
	else:
		lijst_a = [int(x) for x in line.split()]
		operations = 0
		for j in range(0, len(lijst_a) - 1):
			diff = lijst_a[j] - lijst_a[j + 1]
			if diff > 0:
				operations += diff
		print(operations)
	i = 1 - i


for _ in range(int(input())):
	n = int(input())
	A = [int(_) for _ in input().split()]
	s = 0
	c = 0
	for _ in range(n - 1):
		if A[_] + s <= A[_ + 1] + s:
			continue
		else:
			c += A[_] - A[_ + 1]
			s += A[_] - A[_ + 1]
	print(c)


def tc():
	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]
	print(ans)
T = int(input())
for _ in range(T):
	tc()


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


a = input()
for _ in range(int(a)):
	b = input()
	c = input().split(' ')
	list2 = [int(i) for i in c]
	list1 = []
	tag = []
	for i in range(len(list2)):
		if len(tag) == 0:
			tag.append(list2[i])
		elif tag[-1] <= list2[i]:
			tag.append(list2[i])
		else:
			list1.append(tag.copy())
			tag = [list2[i]]
	if len(tag) != 0:
		if list2[-1] >= tag[-1]:
			list1.append(tag.copy())
		else:
			list1.append(tag.copy())
			list1.append([list2[-1]])
	ans = 0
	for i in range(len(list1) - 1, 0, -1):
		if max(list1[i - 1]) > min(list1[i]):
			ans += max(list1[i - 1]) - min(list1[i])
	print(ans)


import sys
input = sys.stdin.readline
for f in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	sol = 0
	for i in range(1, n):
		if a[i] < a[i - 1]:
			sol += a[i - 1]
			sol -= a[i]
	print(sol)


t = int(input())
for h in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	for i in range(n - 1):
		l[i] = l[i + 1] - l[i]
	l[n - 1] = 0
	i = 0
	c = 0
	while i <= n - 1:
		l1 = []
		if l[i] < 0:
			while l[i] < 0:
				l1.append(l[i])
				i = i + 1
		if len(l1) != 0:
			a = sum(l1)
			c = c - a
		i = i + 1
	print(c)


query = int(input())
for i in range(query):
	size = int(input())
	arr = list(map(int, input().split()))
	ans = 0
	for j in range(size - 1):
		ans = ans + max(0, arr[j] - arr[j + 1])
	print(ans)


for _ in range(int(input())):
	n = int(input())
	ls = list(map(int, input().split()))
	mx = ls[0]
	commons = 0
	cnt = 0
	for i in range(n):
		if ls[i] < mx:
			cnt += max(mx - ls[i] - commons, 0)
			commons += mx - ls[i] - commons
		else:
			commons = 0
		mx = max(mx, ls[i])
	print(cnt)


from collections import defaultdict as dd
import math
import sys
input = sys.stdin.readline

def nn():
	return int(input())

def li():
	return list(input())

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

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

def solve():
	n = nn()
	nums = lm()
	needed = 0
	for i in reversed(list(range(1, n))):
		if nums[i] < nums[i - 1]:
			needed += nums[i - 1] - nums[i]
	print(needed)
q = nn()
for _ in range(q):
	solve()


import math
t = int(input())
for q in range(t):
	n = int(input())
	L = [int(i) for i in input().split()]
	L.reverse()
	ma = 0
	for i in range(n - 1, -1, -1):
		ma = max(L[i], ma)
		L[i] = ma - L[i]
	G = [0] * n
	G[0] = L[i]
	for i in range(1, n):
		G[i] = L[i] - L[i - 1]
	sum = 0
	for i in G:
		if i > 0:
			sum += i
	print(sum)


from sys import stdin, stdout
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	ar = list(map(int, stdin.readline().split()))
	mov = 0
	prev = 0
	i = 0
	for i in range(1, n):
		mov += max(ar[i - 1] - ar[i], 0)
	print(mov)


for i in range(int(input())):
	n = int(input())
	x = list(map(int, input().split()))
	lst = list()
	tot = 0
	for i in range(n - 1):
		if x[i] > x[i + 1]:
			c = x[i] - x[i + 1]
			tot = tot + c
	print(tot)


def parr(arr):
	print(*arr, sep=' ')
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	i = 0
	b = []
	while i < n:
		b.append(a[i])
		while i + 1 < n and b[-1] == a[i + 1]:
			i += 1
		i += 1
	m = len(b)
	ans = 0
	i = 1
	while i < m:
		ans += max(0, b[i - 1] - b[i])
		i += 1
	print(ans)


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


import sys
input = sys.stdin.readline
t = int(input())
while t:
	n = int(input())
	l = list(map(int, input().split()))
	mi = l[-1]
	cou = 0
	for i in range(n - 2, -1, -1):
		if l[i] >= mi:
			cou += l[i] - mi
			mi = l[i]
		else:
			mi = l[i]
	print(cou)
	t -= 1


import sys

class COmkarAndWaterslide:

	def solve(self, tc=0):
		for _ in range(int(input())):
			n = int(input())
			a = [int(_) for _ in input().split()]
			ans = 0
			for i in range(1, n):
				if a[i] < a[i - 1]:
					ans += a[i - 1] - a[i]
			print(ans)
solver = COmkarAndWaterslide()
input = sys.stdin.readline
solver.solve()


def find_cost_of_building(supports):
	supports = tuple(supports)
	result = 0
	for (prev_height, next_height) in zip(supports, supports[1:]):
		if prev_height > next_height:
			result += prev_height - next_height
	return result

def main():
	t = int(input())
	for i in range(t):
		n = int(input())
		supports = tuple(map(int, input().split()))
		result = find_cost_of_building(supports)
		print(result)
main()


from sys import stdin, stdout
import bisect
import math
from collections import deque
mod = 10 ** 9 + 7

def st():
	return list(stdin.readline().strip())

def inp():
	return int(stdin.readline())

def li():
	return list(map(int, stdin.readline().split()))

def mp():
	return map(int, stdin.readline().split())

def pr(n):
	stdout.write(str(n) + '\n')

def DFS(dictionary, vertex, visited):
	visited[vertex] = True
	stack = [vertex]
	print(vertex)
	while stack:
		a = stack.pop()
		for i in dictionary[a]:
			if not visited[i]:
				print(i)
				visited[i] = True
				stack.append(i)

def BFS(dictionary, vertex, visited):
	visited[vertex] = True
	q = deque()
	q.append(vertex)
	while q:
		a = q.popleft()
		for i in dictionary[a]:
			if not visited[i]:
				visited[i] = True
				q.append(i)
				print(i)

def soe(limit):
	l = [1] * (limit + 1)
	l[0] = 0
	l[1] = 0
	prime = []
	for i in range(2, limit + 1):
		if l[i]:
			for j in range(i * i, limit + 1, i):
				l[j] = 0
	for i in range(2, limit + 1):
		if l[i]:
			prime.append(i)
	return prime

def segsoe(low, high):
	limit = int(high ** 0.5) + 1
	prime = soe(limit)
	n = high - low + 1
	l = [0] * (n + 1)
	for i in range(len(prime)):
		lowlimit = low // prime[i] * prime[i]
		if lowlimit < low:
			lowlimit += prime[i]
		if lowlimit == prime[i]:
			lowlimit += prime[i]
		for j in range(lowlimit, high + 1, prime[i]):
			l[j - low] = 1
	for i in range(low, high + 1):
		if not l[i - low]:
			if i != 1:
				print(i)

def gcd(a, b):
	while b:
		a = a % b
		(b, a) = (a, b)
	return a

def power(a, n):
	r = 1
	while n:
		if n & 1:
			r = r * a
		a *= a
		n = n >> 1
	return r

def solve():
	n = inp()
	l = li()
	i = n - 2
	a = l[n - 1]
	z = 0
	ans = 0
	while i >= 0:
		if z == 0:
			if l[i] <= a:
				a = l[i]
			else:
				ans += l[i] - a
				z = l[i] - a
				a = l[i]
		elif l[i] <= a:
			a = l[i]
		else:
			c = l[i] - a
			z += c
			ans += c
			a = l[i]
		i -= 1
	print(ans)
for _ in range(inp()):
	solve()


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


for s in [*open(0)][2::2]:
	r = p = 0
	for x in map(int, s.split()):
		r += max(0, p - x)
		p = x
	print(r)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	r = []
	l.reverse()
	m = l[0]
	cm = 0
	c = 0
	for i in l:
		if i <= m:
			m = min(m, i)
		else:
			c += i - m
			m = i
	print(c)


for ii in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	c = 0
	for i in range(n - 2, -1, -1):
		if a[i] <= a[i + 1]:
			pass
		else:
			diff = a[i] - a[i + 1]
			c += diff
	print(c)


t = int(input())
while t:
	t -= 1
	n = int(input())
	ls = list(map(int, input().split()))
	ans = 0
	for i in range(1, len(ls)):
		if ls[i] >= ls[i - 1]:
			pass
		else:
			ans += ls[i - 1] - ls[i]
	print(ans)


for _ in range(int(input())):
	input()
	lst = list(map(int, input().split()))
	(l, r) = (0, 0)
	for i in lst:
		l += max(0, r - i)
		r = i
	print(l)


from sys import stdout, stdin
(_input, _print) = (stdin.readline, stdout.write)
(_range, _max, _int, _min) = (range, max, int, min)

def solution():
	for _ in _range(_int(_input())):
		n = _int(_input())
		arr = [_int(i) for i in _input().split()]
		op = 0
		max_el = arr[0]
		for i in _range(n - 1):
			if arr[i + 1] < arr[i] or arr[i] < max_el:
				if arr[i] > max_el:
					max_el = arr[i]
				min_el = arr[i + 1]
				j = i + 2
				while j < n and arr[j] < arr[j - 1]:
					min_el = _min(min_el, arr[j])
					j += 1
				else:
					if j == n:
						op += max_el - min_el
						break
				op += _min(arr[j], max_el) - min_el
				for k in _range(i + 1, j):
					arr[k] = arr[j]
		print(op)
solution()


t = int(input())

def func():
	n = int(input())
	a = [int(x) for x in input().split()]
	res = 0
	for i in range(1, n):
		if a[i] < a[i - 1]:
			res += a[i - 1] - a[i]
	print(res)
for _ in range(t):
	func()


t = int(input())
ans = []
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	s = 0
	for (j, k) in enumerate(a[:-1]):
		if k > a[j + 1]:
			s += k - a[j + 1]
	ans.append(s)
for i in ans:
	print(i)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	c = 0
	for i in range(1, n):
		a = l[i - 1]
		b = l[i]
		t = a - b
		if t > 0:
			c += t
	print(c)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	dp = [0]
	for i in range(1, n):
		dp += [dp[i - 1] - min(0, l[i] - l[i - 1])]
	print(dp[n - 1])


from sys import stdin
tt = int(stdin.readline())
for loop in range(tt):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	ans = 0
	for i in range(n - 1):
		ans += max(0, a[i] - a[i + 1])
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	count = 0
	k = []
	for i in range(len(a) - 1):
		if a[i] > a[i + 1]:
			k.append(i + 1)
	for i in k:
		count += a[i - 1] - a[i]
	print(count)


import os
import sys
from io import BytesIO, IOBase
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')
from math import gcd, ceil

def pre(s):
	n = len(s)
	pi = [0] * n
	for i in range(1, n):
		j = pi[j - 1]
		while j and s[i] != s[j]:
			j = pi[j - 1]
		if s[i] == s[j]:
			j += 1
		pi[i] = j
	return pi

def prod(a):
	ans = 1
	for each in a:
		ans = ans * each
	return ans

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

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


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	(curr, chk) = ([0, 0], False)
	tot = 0
	for i in range(1, n):
		if l[i] >= l[i - 1]:
			if chk:
				tot += curr[1] - curr[0]
				chk = False
		else:
			curr[0] = l[i]
			if not chk:
				curr[1] = l[i - 1]
				chk = True
	print(tot + (curr[1] - curr[0] if chk else 0))


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


import sys

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s)
	sys.stdout.write('\n')

def wi(n):
	sys.stdout.write(str(n))
	sys.stdout.write('\n')

def wia(a, sep=' '):
	sys.stdout.write(sep.join([str(x) for x in a]))
	sys.stdout.write('\n')

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

def main():
	for _ in range(ri()):
		n = ri()
		a = ria()
		wi(solve(n, a))
main()


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


t = int(input())
for _ in range(t):
	n = int(input())
	inp = [int(i) for i in input().split()]
	maxEle = max(inp)
	res = 0
	for i in range(1, len(inp)):
		if inp[i] < inp[i - 1]:
			res += inp[i - 1] - inp[i]
	print(res)


import sys
input = sys.stdin.readline

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def factorial(x, m):
	val = 1
	while x > 0:
		val = val * x % m
		x -= 1
	return val

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def upper_bound(a, x, lo=0, hi=None):
	if hi == None:
		hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

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

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
from itertools import permutations

def solve():
	n = int(input())
	b = list(map(int, input().split()))
	ps = []
	for i in range(1, n):
		ps.append(b[i] - b[i - 1])
	ans = 0
	for x in ps:
		if x < 0:
			ans += x
	print(abs(ans))
for _ in range(int(input())):
	solve()


import sys
readline = sys.stdin.readline
T = int(readline())
Ans = [None] * T
INF = 10 ** 9 + 7
for qu in range(T):
	N = int(readline())
	A = list(map(int, readline().split()))
	ans = 0
	stack = [INF]
	for a in A[::-1]:
		if stack[-1] < a:
			ans += a - stack[-1]
			stack[-1] = a
		else:
			stack.append(a)
	Ans[qu] = ans
print('\n'.join(map(str, Ans)))


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	temp = [[arr[0]]]
	for i in range(1, n):
		if arr[i] >= temp[-1][-1]:
			temp[-1].append(arr[i])
		else:
			temp.append([arr[i]])
	ans = 0
	for i in range(len(temp) - 1, 0, -1):
		to = temp[i - 1][-1]
		need = to - temp[i][0]
		ans += need
	print(ans)


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


import sys
read = sys.stdin.readline
write = sys.stdout.write
T = int(read())
for t in range(T):
	n = int(read())
	arr = list(map(int, read().split()))
	answer = 0
	for i in range(n - 1):
		answer += max(0, arr[i] - arr[i + 1])
	print(answer)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	min1 = l[0]
	max1 = 0
	c = 0
	flag = 0
	for i in range(n - 1, 0, -1):
		if l[i] < l[i - 1]:
			c += l[i - 1] - l[i]
	print(c)


import sys, math as mt
import heapq as hp
import collections as cc
import bisect as bi
import math as mt
import itertools as it
I = lambda : list(map(int, input().split()))

def main():
	for tc in range(int(input())):
		(n,) = I()
		l = I()
		ans = 0
		curmax = l[0]
		plus = 0
		i = 1
		while i < n:
			if l[i] < curmax:
				tem = l[i]
				i += 1
				while i < n and l[i] < curmax:
					if l[i] >= tem:
						plus += l[i] - tem
						tem = l[i]
					elif l[i - 1] > l[i]:
						plus += abs(l[i - 1] - l[i])
					i += 1
				plus += curmax - tem
			else:
				ans += plus
				plus = 0
				curmax = l[i]
				i += 1
		ans += plus
		print(ans)
main()


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	newa = [a[0]]
	for i in range(1, n):
		if newa[-1] > a[i]:
			if a[i - 1] > a[i]:
				ans += abs(a[i - 1] - a[i])
			newa.append(newa[-1])
		else:
			newa.append(a[i])
	print(ans)


for _ in range(int(input())):
	n = int(input())
	slide = list(map(int, input().split()))
	ops = 0
	maxi = slide[0]
	for i in range(1, len(slide)):
		if slide[i] >= maxi:
			maxi = slide[i]
		elif slide[i - 1] > slide[i]:
			ops += slide[i - 1] - slide[i]
	print(ops)


for _ in range(int(input())):
	am = int(input())
	arr = list(map(int, input().split()))
	s = 0
	for i in range(am - 1):
		s += max(0, arr[i] - arr[i + 1])
	print(s)


import math, sys
from sys import stdin, stdout
from collections import Counter, defaultdict, deque
input = stdin.readline
I = lambda : int(input())
li = lambda : list(map(int, input().split()))

def solve():
	n = I()
	a = li()
	ans = 0
	flag = 0
	m = a[0]
	d = 0
	for i in range(1, n):
		if a[i] < m:
			if flag:
				if a[i - 1] >= a[i]:
					ans += m - a[i] - d
					d = m - a[i]
				else:
					d = m - a[i]
			else:
				d = m - a[i]
				ans += d
				flag = 1
		else:
			flag = 0
			m = a[i]
	print(ans)
for _ in range(I()):
	solve()


import sys
input = sys.stdin.readline
for nt in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	prev = a[0]
	for i in range(1, n):
		if a[i] > a[i - 1]:
			prev = a[i]
			continue
		ans += a[i - 1] - a[i]
	print(ans)


def solve():
	n = int(input())
	A = list(map(int, input().split()))[::-1]
	res = 0
	prev = A[0]
	for i in range(1, len(A)):
		cur = A[i]
		if prev < cur:
			res += cur - prev
		prev = cur
	return res
tc = int(input())
res = []
for _ in range(tc):
	res.append(solve())
for num in res:
	print(num)


import sys
input = sys.stdin.readline
from bisect import bisect_left
from bisect import bisect_right
from math import ceil, factorial

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

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

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
for _ in range(int(input())):
	n = int(input())
	a = int_array()
	ans = 0
	for i in range(n - 1, 0, -1):
		if a[i - 1] > a[i]:
			ans += a[i - 1] - a[i]
	print(ans)


T = int(input())
for t in range(0, T):
	n = int(input())
	given = list(map(int, input().split()))
	ans = given[::-1]
	count = 0
	for i in range(0, n - 1):
		if ans[i] < ans[i + 1]:
			count = count + (ans[i + 1] - ans[i])
	print(count)


for t in range(int(input())):
	n = int(input())
	li = [int(x) for x in input().split()]
	stack = []
	count = 0
	for j in range(1, n):
		if li[j - 1] > li[j]:
			stack.append(j - 1)
			count += 1
	temp = 0
	for j in range(count - 1, -1, -1):
		if stack[j] + 1 < n:
			temp += li[stack[j]] - li[stack[j] + 1]
	print(temp)


from sys import stdin, stdout
import math, queue, heapq
fastinput = stdin.readline
fastout = stdout.write
t = int(input())
while t:
	t -= 1
	n = input()
	a = list(map(int, input().split()))
	minaddend = 0
	stack = []
	for i in a:
		if not stack:
			stack.append(i)
		elif i <= stack[-1]:
			stack.append(i)
		else:
			k = -1
			j = 0
			while stack and stack[-1] < i:
				j = stack.pop()
				if k == -1:
					k = j
			if stack:
				j = i
			stack.append(i)
			minaddend += j - k
	if stack:
		minaddend += stack[0] - stack[-1]
	print(minaddend)


import sys
t = int(input())
for i in range(t):
	n = int(input())
	g = []
	sum = 0
	g = list(map(int, input().split()))
	for j in range(1, n, 1):
		if g[j] < g[j - 1]:
			sum = sum + g[j - 1] - g[j]
	print(sum)


import sys
from collections import defaultdict as dd
from collections import deque
from functools import *
from fractions import Fraction as f
from copy import *
from bisect import *
from heapq import *
from math import *
from itertools import permutations

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')

def inc(d, c):
	d[c] = d[c] + 1 if c in d else 1

def li():
	return [int(xx) for xx in input().split()]

def fli():
	return [float(x) for x in input().split()]

def comp(a, b):
	if a > b:
		return 2
	return 2 if a == b else 0

def gi():
	return [xx for xx in input().split()]

def fi():
	return int(input())

def pro(a):
	return reduce(lambda a, b: a * b, a)

def swap(a, i, j):
	(a[i], a[j]) = (a[j], a[i])

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def isvalid(i, j):
	return 0 <= i < n and 0 <= j < n

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)
t = fi()
mod = 10 ** 9 + 7
while t > 0:
	t -= 1
	n = fi()
	a = li()
	maxi = c = ans = 0
	a.append(max(a))
	for i in range(n + 1):
		maxi = max(maxi, a[i])
		if maxi != a[i]:
			if a[i - 1] > a[i]:
				c += a[i - 1] - a[i]
			else:
				c = max(c, maxi - a[i])
		else:
			ans += c
			c = 0
	print(ans)


t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().rstrip().split()))
	count = 0
	for e in range(n - 1):
		count += max(0, arr[e] - arr[e + 1])
	print(count)


from sys import stdin, stdout
input = stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	out = 0
	l = list(map(int, input().split()))
	for i in range(n - 1):
		out += max(0, l[i] - l[i + 1])
	print(out)


T = int(input())
for _ in range(0, T):
	n = int(input())
	s = [int(x) for x in input().split()]
	ans = 0
	for i in range(len(s) - 1, 0, -1):
		ans += max(0, s[i - 1] - s[i])
	print(ans)


from sys import stdin
from collections import deque
mod = 10 ** 9 + 7
import sys
import random
sys.setrecursionlimit(10 ** 6)
from queue import PriorityQueue
from collections import Counter as cc
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt, factorial, gcd, log2, inf, ceil
import heapq
input = lambda : sys.stdin.readline().rstrip()
from sys import stdin, stdout
from heapq import heapify, heappush, heappop
from itertools import permutations
from math import factorial as f

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p
import sys
t = int(input())
ha = []
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	add = 0
	ans = 0
	for i in range(1, n):
		if l[i] >= l[i - 1]:
			continue
		elif l[i] < l[i - 1]:
			ans += l[i - 1] - l[i]
			add += l[i - 1] - l[i]
	ha.append(ans)
print(*ha)


t = int(input())
for _ in range(t):
	n = int(input())
	array = list(map(int, input().split()))
	k = 0
	for i in range(n - 1):
		if array[i] > array[i + 1]:
			k += array[i] - array[i + 1]
	print(k)


for _ in range(int(input())):
	n = int(input())
	a = [int(s) for s in input().split()]
	m = max(a)
	i1 = 0
	i2 = 0
	f = 1
	c = 0
	for i in range(1, n):
		if a[i] < a[i - 1]:
			c += -a[i] + a[i - 1]
	print(c)


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	m = a[0]
	op = [0 for i in range(n)]
	for i in range(1, n):
		if a[i - 1] >= a[i]:
			op[i] = a[i - 1] - a[i]
		m = max(m, a[i])
	print(sum(op))


t = int(input())
for i in range(t):
	count = 0
	n = int(input())
	list1 = list(map(int, input().split()))
	for i in reversed(range(1, n)):
		if list1[i] < list1[i - 1]:
			count = count + (list1[i - 1] - list1[i])
	print(abs(count))


t = int(input())
i = 0
while i < t:
	n = int(input())
	a = list(map(int, input().split()))
	j = 1
	v = 0
	while j < len(a):
		if a[n - j] != a[n - j - 1] and a[n - j - 1] > a[n - j]:
			v += a[n - j - 1] - a[n - j]
		j += 1
	print(v)
	i += 1


t = int(input())
for o in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	cnt = 0
	for i in range(n - 1):
		if a[n - i - 1] < a[n - i - 2]:
			cnt += a[n - i - 2] - a[n - i - 1]
	print(cnt)


import sys
input = sys.stdin.readline

def check(arr, n):
	res = []
	for i in range(n - 1):
		res.append(arr[i] - arr[i + 1])
	cnt = 0
	for r in res:
		if r > 0:
			cnt += r
	return cnt
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	print(check(arr, n))


for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	if a.count(a[0]) == n:
		print(0)
	else:
		cnt = 0
		maxm = a[0]
		begin = 0
		for i in range(n - 1):
			if a[i] > a[i + 1]:
				cnt += a[i] - a[i + 1]
		print(cnt)


for _ in range(int(input())):
	n = int(input())
	a = [int(o) for o in input().split()]
	s = 0
	for i in range(1, n):
		if a[i] < a[i - 1]:
			s -= a[i] - a[i - 1]
	print(s)


try:
	from sys import stdin, stdout
	t = int(stdin.readline())
	for _ in range(t):
		n = int(stdin.readline())
		a = list(map(int, stdin.readline().split()))
		count = 0
		base = a[0]
		gap = 0
		for i in range(1, n):
			if a[i] < a[i - 1]:
				if base <= a[i]:
					base = i - 1
				else:
					gap = max(base - a[i], gap)
			elif a[i] >= a[i - 1]:
				count += gap
				base = a[i]
				gap = 0
		if gap != 0:
			count += gap
			gap = 0
		stdout.write(str(count) + '\n')
except:
	pass


for s in [*open(0)][2::2]:
	r = last = 0
	for present in map(int, s.split()):
		r += max(0, last - present)
		last = present
	print(r, end=' ')


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	i = 1
	f = 0
	t2 = 0
	max1 = -1
	min1 = 10 ** 10
	while i < n:
		if a[i] < a[i - 1]:
			if i == n - 1:
				if f == 0:
					t2 += a[i - 1] - a[i]
				else:
					t2 += max1 - a[i]
			elif f == 0:
				f = 1
				min1 = a[i]
				max1 = a[i - 1]
			else:
				min1 = a[i]
		elif f == 1:
			t2 += max1 - min1
			max1 = -1
			min1 = 10 ** 10
			f = 0
		else:
			pass
		i += 1
	print(t2)


mod = 10 ** 9 + 7
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	c = 0
	for i in range(n - 1, 0, -1):
		if a[i] < a[i - 1]:
			c += a[i - 1] - a[i]
	print(c)


for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	count = 0
	change = [0]
	m = a[0]
	for i in range(1, n):
		if a[i] > a[i - 1]:
			change.append(i)
			count += min(a[i], a[change[-2]]) - m
			m = a[i]
		else:
			change.append(i)
			m = a[i]
			if i == n:
				change.append(i)
			x = a[change[-2]:change[-1] + 1]
			count += max(x) - a[i]
	print(count)


for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	cnt = 0
	for i in range(n - 1):
		if a[n - 1 - i] < a[n - 1 - i - 1]:
			cnt += a[n - 1 - i - 1] - a[n - 1 - i]
	print(cnt)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

def gift():
	for _ in range(t):
		n = int(input())
		arry = list(map(int, input().split()))
		ans = 0
		for i in range(1, n):
			if arry[i] < arry[i - 1]:
				ans += arry[i - 1] - arry[i]
		yield ans
t = int(input())
ans = gift()
print(*ans, sep='\n')


def solve():
	n = int(input())
	l = [int(x) for x in input().split()]
	ans = 0
	for i in range(n - 1):
		ans += max(0, l[i] - l[i + 1])
	print(ans)
for _ in range(int(input())):
	solve()


t = int(input())
for _ in range(t):
	ans = 0
	n = int(input())
	a = list(map(int, input().split(' ')))
	for x in range(n - 1):
		ans += max(a[x] - a[x + 1], 0)
	print(ans)


for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = []
	for i in range(1, len(a)):
		if a[i - 1] > a[i]:
			b.append(a[i - 1] - a[i])
	if len(b) == 0:
		print(0)
	else:
		print(sum(b))


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ind = 1
	cnt = 0
	while ind < n:
		if a[ind] < a[ind - 1]:
			cnt += a[ind - 1] - a[ind]
			right = ind + 1
			while right < n and a[right] < a[ind - 1]:
				if a[right] < a[right - 1]:
					cnt += a[right - 1] - a[right]
				right += 1
			ind = right
		else:
			ind += 1
	print(cnt)


import sys
import math, bisect
from collections import defaultdict
from itertools import groupby, accumulate
from heapq import heapify, heappop, heappush
from collections import deque, Counter, OrderedDict

def neo():
	return map(int, input().split())

def Neo():
	return list(map(int, input().split()))
for _ in range(int(input())):
	n = int(input())
	A = Neo()
	Ans = 0
	for i in range(1, n):
		Ans += max(0, A[i - 1] - A[i])
	print(Ans)


for _ in range(int(input())):
	n = int(input())
	arr = [int(num) for num in input().split(' ')]
	ans = 0
	for i in range(0, n - 1):
		ans = ans + max(arr[i] - arr[i + 1], 0)
	print(ans)


from sys import stdin, stdout

def INPUT():
	return list((int(i) for i in stdin.readline().split()))

def inp():
	return stdin.readline()

def out(x):
	return stdout.write(x)
import math
import random
import sys
for _ in range(int(input())):
	n = int(input())
	A = INPUT()
	ans = 0
	for i in range(n - 1):
		ans += max(A[i] - A[i + 1], 0)
	print(ans)


from sys import stdin
input = stdin.readline

def A():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		if len(set(a)) == 1:
			print(n)
		else:
			print(1)

def B():
	t = int(input())
	for _ in range(t):
		(n, k) = map(int, input().split())
		a = list(map(int, input().split()))
		d = max(a)
		for i in range(n):
			a[i] = d - a[i]
		if k % 2 == 1:
			print(*a)
		d = max(a)
		for i in range(n):
			a[i] = d - a[i]
		if k % 2 == 0:
			print(*a)

def C():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		ops = 0
		for i in range(n - 1, 0, -1):
			if a[i] < a[i - 1]:
				ops += a[i - 1] - a[i]
		print(ops)

def D():
	t = int(input())
	for _ in range(t):
		print(0)
C()


for _ in range(int(input())):
	n = int(input())
	(*arr,) = map(int, input().split())
	arr = arr[::-1]
	mn = arr[0]
	ans = 0
	for v in arr:
		if v > mn:
			ans += v - mn
		mn = v
	print(ans)


for _ in range(int(input())):
	n = int(input())
	ar = [int(x) for x in input().split()]
	ans = 0
	mx = ar[0]
	for i in range(n - 2, -1, -1):
		ans += max(ar[i] - ar[i + 1], 0)
	print(ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	s = 0
	d = 0
	x = False
	for i in range(1, len(a)):
		if a[i - 1] > a[i]:
			if x:
				s += max(a[i - 1] - a[i], d)
				d = a[i - 1] - a[i]
				x = True
			else:
				s += a[i - 1] - a[i]
		else:
			x = False
	print(s)


input = __import__('sys').stdin.readline
for _ in range(int(input())):
	n = int(input())
	s = list(map(int, input().split()))
	mx = s[0]
	ans = 0
	cur = s[-1]
	for i in range(n - 2, -1, -1):
		if s[i] > cur:
			ans += s[i] - cur
			cur = s[i]
		else:
			cur = s[i]
	print(ans)


q = int(input())
while q:
	q -= 1
	n = int(input())
	a = list(reversed([int(x) for x in input().split()]))
	ans = 0
	for i in range(1, n):
		ans += max(0, a[i] - a[i - 1])
	print(ans)


t = int(input())
while t:
	x = []
	n = int(input())
	tmp = input()
	x = tmp.split()
	x = list(map(int, x))
	res = 0
	for i in range(1, n):
		if x[i] < x[i - 1]:
			res += x[i - 1] - x[i]
	print(res)
	t -= 1


import math
for _ in range(int(input())):
	n = int(input())
	lst = list(map(int, input().split()))
	mx = max(lst)
	i = 0
	ans = 0
	while i < n:
		j = i + 1
		while j < n:
			if lst[j] >= lst[j - 1]:
				j += 1
			else:
				break
		ult = lst[j - 1]
		mn = lst[j - 1]
		while j < n:
			if lst[j] <= mn:
				mn = min(mn, lst[j])
				j += 1
			else:
				break
		ans += ult - mn
		i = j
	print(ans)


import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	for i in range(n - 1):
		if a[i] > a[i + 1]:
			ans += abs(a[i] - a[i + 1])
	print(ans)


import sys
LI = lambda : list(map(int, sys.stdin.readline().strip('\n').split()))
MI = lambda : map(int, sys.stdin.readline().strip('\n').split())
SI = lambda : sys.stdin.readline().strip('\n')
II = lambda : int(sys.stdin.readline().strip('\n'))
for _ in range(II()):
	n = II()
	a = LI()[::-1]
	ans = p = 0
	while p < n:
		c = p + 1
		if c == n:
			break
		while c < n and a[c] > a[c - 1]:
			c += 1
		c -= 1
		if a[c] > a[p]:
			ans += a[c] - a[p]
		p = c + 1
	print(ans)


T = int(input())
while T > 0:
	n = int(input())
	arr = list(map(int, input().split()))
	res = 0
	index = 1
	prev = arr[0]
	while index < n:
		if arr[index] >= arr[index - 1]:
			prev = arr[index]
			index += 1
		else:
			while index < n and arr[index] < arr[index - 1]:
				need = prev - arr[index]
				index += 1
			res += need
	print(res)
	T -= 1


cases = int(input())
for _ in range(cases):
	n = int(input())
	c = list(map(int, input().split()))
	if c == sorted(c) or len(c) == 1:
		print(0)
	elif len(c) == 2:
		print(abs(c[0] - c[1]))
	else:
		tot = 0
		t = c[-1]
		for i in range(n - 2, -1, -1):
			if c[i] > t:
				tot += c[i] - t
			t = c[i]
		print(tot)


for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	ans = 0
	prev = a[n - 1]
	idx = [n - 2 - i for i in range(0, n - 1)]
	for i in idx:
		if a[i] > prev:
			ans += a[i] - prev
		prev = a[i]
	print(ans)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	i = 1
	ans = 0
	while i < n:
		while i < n and arr[i] >= arr[i - 1]:
			i += 1
		if i == n:
			break
		check = arr[i - 1]
		start = i
		temp = [arr[i]]
		i += 1
		while i < n and arr[i] <= arr[i - 1]:
			temp.append(arr[i])
			i += 1
		value = 0
		for j in range(len(temp)):
			add = check - (temp[j] + value)
			ans += add
			value += add
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	f = [int(i) for i in input().split()]
	i = 1
	total = 0
	while i < len(f):
		if f[i] < f[i - 1]:
			total += f[i - 1] - f[i]
			j = i
			while j < len(f) - 1 and f[j] < f[i - 1]:
				if f[j] > f[j + 1]:
					total += f[j] - f[j + 1]
				j += 1
			i = j
		i += 1
	print(total)


from sys import stdin, stdout
test_cases = int(stdin.readline())
result = []
for _ in range(test_cases):
	n = int(stdin.readline())
	arr_a = list(map(int, stdin.readline().split()))
	count = 0
	for i in range(n - 1):
		if arr_a[i] <= arr_a[i + 1]:
			pass
		else:
			count += arr_a[i] - arr_a[i + 1]
	result.append(str(count))
stdout.write('\n'.join(result))


import os
import re
import sys
from bisect import bisect, bisect_left, insort, insort_left
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from fractions import gcd
from io import BytesIO, IOBase
from itertools import accumulate, combinations, combinations_with_replacement, groupby, permutations, product
from math import acos, asin, atan, ceil, cos, degrees, factorial, hypot, inf, log2, pi, radians, sin, sqrt, tan
from operator import itemgetter, mul
from string import ascii_lowercase, ascii_uppercase, digits

def inp():
	return int(input())

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

def instr():
	s = input()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())

def main():
	t = inp()
	for _ in range(t):
		n = inp()
		a = inlist()
		a.append(1000000000000000)
		d = a[0]
		ans = 0
		mini = d
		for i in range(1, n + 1):
			if a[i] < a[i - 1]:
				mini = min(a[i], mini)
			else:
				ans += d - mini
				d = a[i]
				mini = d
		print(ans)
main()


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


import math
import bisect
import copy
import time
from collections import Counter
for _ in range(int(input())):
	n = int(input())
	l = [int(x) for x in input().split()]
	mx = l[0]
	mi = -1
	c = 0
	f = 0
	for i in range(n - 1, 0, -1):
		if l[i] < l[i - 1]:
			c += l[i - 1] - l[i]
	print(c)


test = int(input())
for _ in range(test):
	n = int(input())
	arr = list(map(int, input().split()))
	inc = 0
	for i in range(1, n):
		if arr[i] < arr[i - 1]:
			inc += arr[i - 1] - arr[i]
	print(inc)


for t in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split(' ')]
	q = 0
	for i in range(1, n):
		q += max(0, a[i - 1] - a[i])
	print(q)


import time, math as mt, bisect as bs, sys
from sys import stdin, stdout
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi = 3.141592653589793

def II():
	return int(stdin.readline())

def IO():
	return stdin.readline()

def IP():
	return map(int, stdin.readline().split())

def L():
	return list(map(int, stdin.readline().split()))

def P(x):
	return stdout.write(str(x) + '\n')

def PI(x, y):
	return stdout.write(str(x) + ' ' + str(y) + '\n')

def lcm(a, b):
	return a * b // gcd(a, b)

def gcd(a, b):
	if a == 0:
		return b
	elif b == 0:
		return a
	if a > b:
		return gcd(a % b, b)
	else:
		return gcd(a, b % a)

def readTree():
	v = int(input())
	adj = [set() for i in range(v + 1)]
	for i in range(v - 1):
		(u1, u2) = In()
		adj[u1].add(u2)
		adj[u2].add(u1)
	return (adj, v)

def bfs(adj, v):
	visited = [False] * (v + 1)
	q = deque()
	while q:
		pass

def sieve():
	li = [True] * 1000001
	(li[0], li[1]) = (False, False)
	for i in range(2, len(li), 1):
		if li[i] == True:
			for j in range(i * i, len(li), i):
				li[j] = False
	prime = []
	for i in range(1000001):
		if li[i] == True:
			prime.append(i)
	return prime

def setBit(n):
	count = 0
	while n != 0:
		n = n & n - 1
		count += 1
	return count
mx = 10 ** 7
spf = [mx] * (mx + 1)

def SPF():
	spf[1] = 1
	for i in range(2, mx + 1):
		if spf[i] == mx:
			spf[i] = i
			for j in range(i * i, mx + 1, i):
				if i < spf[j]:
					spf[j] = i
	return
mod = 10 ** 9 + 7

def solve():
	n = II()
	h = L()
	mx = 0
	lmov = 0
	ans = 0
	for i in range(n):
		if h[i] < mx:
			req = mx - h[i]
			if req > lmov:
				ans += req - lmov
			lmov = req
		else:
			lmov = 0
			mx = h[i]
	P(ans)
	return
t = II()
for i in range(t):
	solve()


ls = lambda : list(map(int, input().split()))
ip = lambda : int(input())
sip = lambda : input()
r = lambda a: range(a)
lcm = lambda a, b: abs(a * b) // math.gcd(a, b)
t = ip()
for _ in r(t):
	_s = ip()
	supports = ls()
	ops = 0
	prev = 0
	pos = 0
	for i in range(_s - 1):
		if supports[i] > supports[i + 1]:
			op = supports[i] - supports[i + 1]
			supports[i + 1] += op
			if pos == i - 1:
				if op > prev:
					ops -= prev
					ops += op
			else:
				ops += op
			prev = op
			pos = i
	print(ops)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().rstrip().split()))
	mx = a[0]
	dp = [0] * n
	for i in range(1, n):
		if a[i] >= mx:
			mx = a[i]
			dp[i] = 0
		elif a[i] >= a[i - 1]:
			dp[i] = 0
		else:
			dp[i] = abs(a[i] - a[i - 1])
	print(sum(dp))


import sys
input = sys.stdin.readline
t = int(input())
for i in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	maxa = a[0]
	mina = 0
	ans = 0
	for i in range(1, n):
		if a[i] < a[i - 1]:
			ans += a[i - 1] - a[i]
			mina = a[i]
	print(ans)


t = int(input())
while t:
	t -= 1
	n = int(input())
	arr = list(map(int, input().split()))[:n]
	c = 0
	i = 0
	j = 0
	while i < n:
		i += 1
		if i < n and arr[i - 1] > arr[i]:
			j = i
			while j < n and arr[j - 1] > arr[j] and (arr[i - 1] > arr[j]):
				j += 1
			c += arr[i - 1] - min(arr[i:j + 1])
		if j > i:
			i = j
	print(c)


def min_operation(n, l):
	s = 0
	l.reverse()
	for i in range(n - 1):
		if l[i] < l[i + 1]:
			s += l[i + 1] - l[i]
	return s
for t in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	print(min_operation(n, l))


from sys import stdin
input = stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	(*a,) = map(int, input().split())
	ans = 0
	for i in range(n - 1):
		ans += max(0, a[i] - a[i + 1])
	print(ans)


from math import *
from copy import *
from string import *
from random import *
from sys import stdin, stdout
from sys import maxsize
from operator import *
from itertools import *
from collections import Counter
import math
import math
import time
from queue import Queue

def seive(n):
	l = [True]
	l = l * (n + 1)
	for i in range(2, int(sqrt(n)) + 1):
		if l[i] == True:
			val = i * i
			while val < len(l):
				l[val] = False
				val += i
	prime = []
	for i in range(2, len(l)):
		if l[i] == True:
			prime.append(i)
	return prime

def dp(l, i, n, val, ans):
	if i >= n or val < 0:
		return 1000000
	elif val == 0:
		return 0
	else:
		if ans[i] == 1000000:
			ans[i] = min(min(1 + dp(l, i + 1, n, val - l[i], ans), 1 + dp(l, i, n, val - l[i], ans)), dp(l, i + 1, n, val, ans))
		return ans[i]
from queue import Queue

def factors(n):
	l = []
	for i in range(1, int(sqrt(n)) + 1):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
	return l

def check1(s, v, x):
	while True:
		if v not in s:
			return v
		else:
			v -= 1

def check2(s, v, x):
	while True:
		if v not in s:
			return v
		else:
			v += 1

def up(n):
	j = n - 1
	while j > 0:
		if n % j == 0:
			break
		j -= 1
	return j

def fac(n):
	c = 1
	i = 1
	while i <= n:
		c *= i
		i += 1
	return c

def check_happy(n):
	ss = set()
	print(n)
	while n != 1:
		val = n
		s = 0
		print(val)
		while val != 0:
			s += (val % 10) ** 2
			val = val // 10
		print(val)
		print('hi')
		if val in ss:
			return False
		else:
			n = val
			ss.add(n)
	return True

def update(a, b):
	c = 1
	val = a
	while a < b:
		print(c, a)
		c += c
		a += a
	print(1)
	while a > b:
		print()
		a -= val
		c -= 1
	return c
import random as rand

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)
from itertools import permutations

def insertion_sort(arr):
	for i in range(len(arr)):
		j = i
		while j > 0:
			if arr[j] < arr[j - 1]:
				temp = arr[j]
				arr[j] = arr[j - 1]
				arr[j - 1] = temp
			j -= 1
	return arr

def quick_sort(arr, low, high):
	i = low
	j = high
	while i < j:
		if arr[i] > arr[low] and arr[j] < arr[low]:
			temp = arr[i]
			arr[i] = arr[j]
			arr[j] = arr[i]
			i += 1
			j -= 1
		elif arr[i] <= arr[low]:
			i += 1
		elif arr[j] >= arr[low]:
			j -= 1
	print(i, j)
	toto = arr[j]
	arr[j] = arr[low]
	arr[low] = toto
	return j

def dodo(arr, low, high):
	if low < high:
		val = quick_sort(arr, low, high)
		dodo(arr, low, val - 1)
		dodo(arr, val + 1, high)

def dp(arr, c, n, k, z, ans):
	if k == 0:
		return ans
	elif c == 0:
		return dp(arr, c + 1, n, k - 1, z, ans + arr[c + 1])
	elif c == n - 1:
		if z == 0:
			return 0
		else:
			return dp(arr, c - 1, n, k - 1, z - 1, ans + arr[c - 1])
	elif z == 0:
		return dp(arr, c + 1, n, k - 1, z, ans + arr[c + 1])
	else:
		return max(dp(arr, c + 1, n, k - 1, z, ans + arr[c + 1]), dp(arr, c - 1, n, k - 1, z - 1, ans + arr[c - 1]))

def check(arr, val):
	a = -1
	for i in range(len(arr)):
		if arr[i][len(arr[i]) - 1] == val:
			a = i
			break
	return a

def reverse(s, i, ans):
	if i >= len(s):
		return ans
	else:
		return reverse(s, i + 1, s[i] + ans)

def update(arr, i, j, n, m):
	if i >= 0 and i < n and (j >= 0) and (j < m):
		if arr[i][j] == 1:
			arr[i][j] == 2
			return [i, j]
	return [-1, -1]
t = int(stdin.readline())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split(' ')))
	j = n - 1
	ans = 0
	while j > 0:
		if l[j] < l[j - 1]:
			ans += l[j - 1] - l[j]
		j -= 1
	print(ans)


answer = []
t = int(input())
for _ in range(t):
	n = int(input())
	liste = list(map(int, input().split(' ')))
	count = 0
	for i in range(n - 1):
		if liste[i] > liste[i + 1]:
			goal = liste[i]
			min_s = liste[i + 1]
			max_s = liste[i + 1]
			start = i + 1
			end = i + 1
			direction = 0
			while end < n - 1 and liste[end + 1] < goal:
				if liste[end] <= liste[end + 1]:
					if liste[end] == liste[end + 1]:
						direction = 0
					else:
						direction = 1
					if liste[end + 1] >= max_s:
						count += liste[end + 1] - min_s
						max_s = liste[end + 1]
						min_s = liste[end + 1]
					end += 1
				elif direction == 1 and liste[end] >= liste[end + 1]:
					count += liste[end] - min_s
					min_s = liste[end + 1]
					end += 1
					direction = -1
				else:
					min_s = liste[end + 1]
					end += 1
			count += goal - min_s
			liste[start:end + 1] = [goal for i in range(start, end + 1)]
	answer.append(str(count))
print('\n'.join(answer))


for _ in range(int(input())):
	n = int(input())
	li = list(map(int, input().split()))
	c = 0
	m = 0
	z = 0
	for i in range(n - 1):
		c += max(li[i] - li[i + 1], 0)
	print(c)


def solve(arr, n):
	if n == 1:
		return 0
	new = []
	for i in range(1, n):
		new.append(arr[i] - arr[i - 1])
	mn = min(new)
	if mn >= 0:
		return 0
	ans = 0
	i = 0
	while i < len(new):
		if new[i] < 0:
			local = 0
			while i < len(new) and new[i] < 0:
				local += new[i]
				i += 1
			ans += local
		else:
			i += 1
	return abs(ans)
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	print(solve(arr, n))


for _ in range(int(input())):
	N = int(input())
	A = list(map(int, input().split()))
	A.reverse()
	count = 0
	for i in range(1, N):
		if A[i] > A[i - 1]:
			count += A[i] - A[i - 1]
	print(count)


from sys import stdin
input = lambda : stdin.readline().strip()
for _ in range(int(input())):
	n = int(input())
	lst = [int(i) for i in input().split()]
	nd = 0
	for i in range(1, n):
		nd += max([0, lst[i - 1] - lst[i]])
	print(nd)


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


def main():
	t = int(input())
	for ii in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		c = 0
		for i in range(len(a) - 1):
			if a[i] > a[i + 1]:
				c = c + (a[i] - a[i + 1])
		print(c)
main()


import sys
sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]
for _ in range(II()):
	n = II()
	aa = LI()
	pa = aa[-1]
	ans = 0
	for a in aa[-2::-1]:
		if a > pa:
			ans += a - pa
		pa = a
	print(ans)


import sys

def input():
	return sys.stdin.readline().strip()

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 ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7
for _ in range(INT()):
	N = INT()
	A = LIST() + [INF]
	stack = []
	mx = A[0]
	lo = A[0]
	ans = 0
	up = True
	for i in range(1, N + 1):
		if A[i - 1] <= A[i] and up:
			if A[i] >= mx:
				ans += mx - lo
				lo = A[i]
				mx = A[i]
		elif A[i - 1] <= A[i] and (not up):
			up = True
			lo = A[i - 1]
		elif A[i - 1] > A[i] and up:
			up = False
			ans += A[i - 1] - lo
			lo = A[i - 1]
	ans += mx - lo
	print(ans)


for _ in range(int(input())):
	input()
	a = list(map(int, input().split()))
	previous = a[-1]
	it = 0
	for el in reversed(a[:-1]):
		if el > previous:
			it += el - previous
		previous = el
	print(it)


for _ in [0] * int(input()):
	n = int(input())
	a = [int(x) for x in input().split()]
	count = 0
	p = a[0]
	for i in range(1, n):
		count += max(0, p - a[i])
		p = a[i]
	print(count)


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	tot = 0
	for i in reversed(range(n - 1)):
		if a[i] - a[i + 1] > 0:
			tot += a[i] - a[i + 1]
	print(tot)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	m = arr[0]
	p = arr[0]
	res = 0
	for i in range(1, n):
		if arr[i] > arr[i - 1]:
			res += p - arr[i - 1]
			p = arr[i]
			m = arr[i]
		else:
			pass
	print(res + (p - arr[-1]))


for t in range(int(input())):
	n = int(input())
	b = [int(x) for x in input().split()]
	c = 0
	for i in range(n - 1):
		if b[n - 1 - i] < b[n - i - 2]:
			c = c + b[n - 1 - i - 1] - b[n - 1 - i]
	print(c)


l = []
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	sum = 0
	t = a[-1]
	for i in range(n - 2, -1, -1):
		t = min(t, a[i])
		if a[i] > a[i + 1]:
			sum = sum + a[i] - t
			t = a[i]
	l.append(sum)
for i in l:
	print(i)


t = int(input())
while t != 0:
	n = int(input())
	arrN = list(map(int, input().split()))
	incrementNum = 0
	for i in range(n - 1):
		if arrN[i] > arrN[i + 1]:
			incrementNum += arrN[i] - arrN[i + 1]
	print(incrementNum)
	t -= 1


import sys
import string
import math
from collections import defaultdict
from functools import lru_cache
from collections import Counter
from fractions import Fraction

def mi(s):
	return map(int, s.strip().split())

def lmi(s):
	return list(mi(s))

def tmi(s):
	return tuple(mi(s))

def mf(f, s):
	return map(f, s)

def lmf(f, s):
	return list(mf(f, s))

def js(lst):
	return ' '.join((str(d) for d in lst))

def jsns(lst):
	return ''.join((str(d) for d in lst))

def line():
	return sys.stdin.readline().strip()

def linesp():
	return line().split()

def iline():
	return int(line())

def mat(n):
	matr = []
	for _ in range(n):
		matr.append(linesp())
	return matr

def matns(n):
	mat = []
	for _ in range(n):
		mat.append([c for c in line()])
	return mat

def mati(n):
	mat = []
	for _ in range(n):
		mat.append(lmi(line()))
	return mat

def pmat(mat):
	for row in mat:
		print(js(row))

def solve(arr):
	stack = []
	cost = 0
	i = 0
	while i < len(arr):
		n = arr[i]
		if len(stack) == 0:
			stack.append(n)
		else:
			elems = []
			while stack and stack[-1] <= n:
				elems.append(stack[-1])
				stack.pop()
			elems.reverse()
			if len(stack) > 0:
				diff = 0
				for elem in elems:
					cost += n - (elem + diff)
					diff += n - (elem + diff)
				stack.append(n)
			else:
				stack.append(n)
				n = elems[0]
				diff = 0
				for elem in elems:
					cost += n - (elem + diff)
					diff += n - (elem + diff)
		i += 1
	while len(stack) > 1:
		cost += stack[-2] - stack[-1]
		stack.pop()
	print(cost)

def main():
	t = iline()
	for _ in range(t):
		line()
		solve(lmi(line()))
main()


import math
import os
import random
import re
import sys
from collections import defaultdict, Counter, deque
import heapq
from functools import lru_cache
from itertools import accumulate, chain, combinations, permutations, groupby, zip_longest
from math import floor, ceil, sqrt

def solve(arr):
	return sum((max(0, a - b) for (a, b) in zip(arr, arr[1:])))
t = int(input())
results = []
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	results += (solve(arr),)
for res in results:
	print(res)


tests = int(input())
while tests > 0:
	tests -= 1
	n = int(input())
	d = list(map(int, input().split()))
	ans = 0
	dop = []
	for i in range(0, n - 1):
		if d[i + 1] < d[i]:
			dop.append(i)
	for i in range(len(dop) - 1, -1, -1):
		ans += d[dop[i]] - d[dop[i] + 1]
	print(ans)


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

def I():
	return int(sys.stdin.readline())

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def YES(c):
	return IF(c, 'YES', 'NO')

def Yes(c):
	return IF(c, 'Yes', 'No')

def main():
	t = I()
	rr = []
	for _ in range(t):
		n = I()
		a = LI()
		r = 0
		for (b, c) in zip(a, a[1:]):
			if b > c:
				r += b - c
		rr.append(r)
	return JA(rr, '\n')
print(main())


import sys, io, os
BUFSIZE = 8192

class FastIO(io.IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = io.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(io.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):
	(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()
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
T = int(input())
for _ in range(T):
	N = int(input())
	A = list(map(int, input().split()))
	ans = 0
	for (a1, a2) in zip(A, A[1:]):
		if a1 > a2:
			ans += a1 - a2
	print(ans)


from collections import defaultdict

def ii():
	return int(input())

def si():
	return input()

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

def mi():
	return map(int, input().split())
t = ii()
for _ in range(t):
	n = ii()
	l = li()
	arr = [0] * n
	for i in range(n - 1):
		if l[i] > l[i + 1]:
			arr[i] = l[i] - l[i + 1]
	ans = sum(arr)
	print(ans)


test = int(input())
for _ in range(test):
	n = int(input())
	arr = input().split()
	count = 0
	for i in range(n - 1):
		x = int(arr[i]) - int(arr[i + 1])
		if x > 0:
			count += x
	print(count)


t = int(input())
for x in range(t):
	l = int(input())
	sup = list(map(int, input().split()))
	op = flag = 0
	for i in range(1, l):
		op += max(0, sup[i - 1] - sup[i])
	print(op)


import os
import sys
from io import BytesIO, IOBase
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')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def print_list(l):
	print(' '.join(map(str, l)))
for _ in range(N()):
	n = N()
	a = RLL()
	a = [a[0]] + [a[i] for i in range(1, n) if a[i] != a[i - 1]]
	high = []
	low = []
	if len(a) == 1:
		print(0)
	else:
		for i in range(1, len(a) - 1):
			if a[i] > a[i - 1] and a[i] > a[i + 1]:
				high.append(a[i])
			elif a[i] < a[i - 1] and a[i] < a[i + 1]:
				low.append(a[i])
		if a[1] < a[0]:
			high = [a[0]] + high
		if a[-1] < a[-2]:
			low.append(a[-1])
		res = 0
		for i in range(len(high)):
			res += high[i] - low[i]
		print(res)


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	count = 0
	for j in range(1, n):
		if l[j] < l[j - 1]:
			count += l[j - 1] - l[j]
	print(count)


kase = int(input().strip())
while kase > 0:
	kase = kase - 1
	n = map(int, input().strip().split())
	a = list(map(int, input().split()))
	ans = 0
	for (i, ai) in enumerate(a):
		if i == 0:
			continue
		elif a[i - 1] > ai:
			ans = ans + a[i - 1] - ai
	print(ans)


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


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l = [-1] + l + [max(l)]
	a = []
	low = []
	x = 1
	for i in range(1, n + 1):
		if l[i - 1] < l[i] and l[i + 1] <= l[i]:
			a.append(l[i])
		if l[i - 1] >= l[i] and l[i + 1] > l[i]:
			a.append(l[i])
			low.append((l[i], x))
			x += 2
	a.append(l[n + 1])
	peak = [[] for _ in range(len(a))]
	for i in range(len(a)):
		if i % 2 == 1:
			peak[i] = [i - 1, i + 1, i - 2, i + 2]
	low.sort()
	sol = 0
	for ll in low:
		(v, ind) = ll
		(lnei, rnei) = (peak[ind][2], peak[ind][3])
		if a[peak[ind][0]] > a[peak[ind][1]]:
			sol += a[peak[ind][1]] - v
			if rnei < len(a):
				peak[rnei][2] = peak[ind][2]
				peak[rnei][0] = peak[ind][0]
			if lnei >= 0:
				peak[lnei][3] = peak[ind][3]
		else:
			sol += a[peak[ind][0]] - v
			if lnei >= 0:
				peak[lnei][3] = peak[ind][3]
				peak[lnei][1] = peak[ind][1]
			if rnei < len(a):
				peak[rnei][2] = peak[ind][2]
	print(sol)


def solve(arr, n, ans):
	total = 0
	for i in range(n - 1):
		total += max(0, arr[i] - arr[i + 1])
	ans.append(str(total))

def main():
	t = int(input())
	ans = []
	for i in range(t):
		n = int(input())
		arr = list(map(int, input().split()))
		solve(arr, n, ans)
	print('\n'.join(ans))
main()


from sys import stdin
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1000000000.0) + 7
inf = float('inf')
(t,) = gil()
for _ in range(t):
	(n,) = gil()
	arr = gil()
	ans = 0
	prevMax = arr[0]
	for i in range(1, n):
		if arr[i] < arr[i - 1]:
			ans += arr[i - 1] - arr[i]
		else:
			prevMax = max(arr[i], prevMax)
	print(ans)


import math
import sys
import itertools
import random
import bisect
import heapq
import collections

def lcm(x, y):
	return x * y // math.gcd(x, y)

def hcf(x, y):
	return math.gcd(x, y)

def primes(n):
	prime = [True for _ in range(0, n + 1)]
	res = []
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[p] = False
		p += 1
	for i in range(0, n + 1):
		if prime[i] == True:
			res.append(i)
	return res

def primeFactors(n):
	res = []
	while n % 2 == 0:
		res.append(2)
		n //= 2
	for i in range(3, math.sqrt(n) + 1, 2):
		while n % i == 0:
			res.append(i)
			n //= i
	if n > 2:
		res.append(n)
	return res
for _ in range(0, int(input())):
	n = int(input())
	l = list(map(int, input().strip().split()))
	l.reverse()
	minimum = l[0]
	res = 0
	for i in range(1, n):
		if l[i] <= minimum:
			minimum = l[i]
		else:
			res += l[i] - minimum
			minimum = l[i]
	print(res)


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
cases = int(input())
for t in range(cases):
	n = int(input())
	a = list(map(int, input().split()))
	s = 0
	for i in range(n - 1):
		s += max(a[i] - a[i + 1], 0)
	print(s)


for _ in range(int(input())):
	x = int(input())
	li = list(map(int, input().split()))
	ans = 0
	k = li[0]
	for i in range(1, x):
		li[i] += ans
		if k > li[i]:
			ans += k - li[i]
		else:
			k = li[i]
	print(ans)


t = int(input())

def waterslide(n, arr):
	sum = 0
	for i in range(len(arr) - 1, 0, -1):
		if arr[i] < arr[i - 1]:
			sum += arr[i - 1] - arr[i]
	return sum
for __ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	print(waterslide(n, arr))


import random

def solve(n, a):
	ans = 0
	temp = 0
	high = a[0]
	for i in range(1, n):
		if a[i] > a[i - 1]:
			high = a[i]
			ans += temp
			temp = 0
		else:
			temp = high - a[i]
	if temp > 0:
		ans += temp
	return ans

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		print(solve(n, a))

def debug():
	while True:
		n = random.randint(1, 5)
		a = [random.randint(1, 10) for _ in range(n)]
		print()
		print(a)
		print(solve(n, a))

def debug2():
	n = 5
	a = [8, 1, 1, 5, 1]
	ans = solve(n, a)
	assert ans == 11, f'{ans}'
main()


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


import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(x) for x in input().split()]
	starts = []
	for i in range(1, n):
		if arr[i] < arr[i - 1]:
			starts.append(i)
	cnt = 0
	for i in range(len(starts) - 1, -1, -1):
		sIdx = starts[i]
		cnt += arr[sIdx - 1] - arr[sIdx]
	print(cnt)


n = int(input())
for _ in range(n):
	n = int(input())
	ll = list(map(int, input().split()))
	min = 0
	sum1 = 0
	for i in range(len(ll) - 1):
		if ll[i + 1] < ll[i]:
			sum1 = sum1 + abs(ll[i] - ll[i + 1])
	print(sum1)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	x = 0
	x = [max(0, l[i] - l[i + 1]) for i in range(n - 1)]
	print(sum(x))


import sys, collections, math

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_array():
	return list(map(int, sys.stdin.readline().strip().split()))

def input():
	return sys.stdin.readline().strip()
mod = 1000000007
for _ in range(int(input())):
	n = int(input())
	arr = get_array()
	cnt = 0
	for i in range(n - 1):
		if arr[i + 1] < arr[i]:
			cnt += arr[i + 1] - arr[i]
	print(abs(cnt))


def slide(arr):
	cnt = 0
	i = 0
	while i < n - 1:
		x = i
		while arr[i] >= arr[i + 1]:
			i += 1
			if i == n - 1:
				break
		y = i
		for z in range(x, y):
			cnt += arr[z] - arr[z + 1]
		if i == n - 1:
			break
		i += 1
	return cnt
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().strip().split()))
	result = slide(a)
	print(result)


import math

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	ans = 0
	for i in range(n - 1):
		ans += max(0, a[i] - a[i + 1])
	return ans
t = int(input())
while t > 0:
	t -= 1
	print(solve())


for x in range(int(input())):
	n = int(input())
	m = list(map(int, input().split()))
	k = 0
	h = m[0]
	s = 0
	t = 0
	r = 0
	for i in range(1, n - 1):
		if m[i] > m[i - 1] and m[i] >= m[i + 1]:
			h = m[i]
		elif m[i] < m[i - 1] and m[i] <= m[i + 1]:
			s += h - m[i]
	if m[n - 1] < m[n - 2]:
		s += h - m[n - 1]
	print(s)


t = int(input())
while t != 0:
	t -= 1
	n = int(input())
	arr = list(map(int, input().split(' ')))
	s = 0
	for i in range(1, n):
		if arr[i] < arr[i - 1]:
			s = s + arr[i - 1] - arr[i]
	print(s)


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	ans = 0
	i = 1
	while i < n and i >= 0:
		mine = 100000000000000000
		if l[i] < l[i - 1]:
			mine = l[i]
			maxe = l[i - 1]
			while i < n and l[i] < l[i - 1]:
				mine = min(mine, l[i])
				i += 1
			ans += maxe - mine
		i += 1
	print(ans)


def solve(n, ll):
	cnt = 0
	for i in range(1, n):
		if ll[i] < ll[i - 1]:
			cnt += ll[i - 1] - ll[i]
	return cnt
t = int(input())
while t != 0:
	n = int(input())
	ll = list(map(int, input().split()))
	print(solve(n, ll))
	t -= 1


for _ in range(int(input())):
	x = int(input())
	li = list(map(int, input().split()))
	ans = 0
	for i in range(1, x):
		ans += max(0, li[i - 1] - li[i])
	print(ans)


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


import random

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def lcm(a, b):
	return a * b / gcd(a, b)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	curr_max = a[0]
	curr_min = a[0]
	ans = 0
	for i in range(1, n):
		if a[i] < a[i - 1] and a[i] < curr_min:
			ans += a[i - 1] - a[i]
		if a[i] > a[i - 1]:
			curr_min = a[i]
		curr_min = min(curr_min, a[i])
		curr_max = max(curr_max, a[i])
	print(ans)


import os
import heapq
import sys
import math
import operator
from collections import defaultdict, deque
from io import BytesIO, IOBase

def inpt():
	return [int(k) for k in input().split()]

def main():
	for _ in range(int(input())):
		n = int(input())
		ar = inpt()
		q = deque()
		ans = 0
		for i in range(n - 1, -1, -1):
			if not q:
				q.append((ar[i], 1))
			else:
				mx = 0
				while q and q[len(q) - 1][0] < ar[i]:
					(val, ct) = q.pop()
					mx = max(mx, abs(ar[i]) - val)
				ans += mx
				q.append((ar[i], 0))
		print(ans)
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')
main()


t = int(input())
for i in range(0, t):
	n = int(input())
	a = [int(a) for a in input().split()]
	cnt = 0
	for i in range(0, n - 1):
		cnt += max(a[i] - a[i + 1], 0)
	print(cnt)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	l = a[-1]
	r = 0
	i = n - 2
	while i >= 0:
		if a[i] > l:
			r += a[i] - l
			l = a[i]
		elif a[i] < l:
			l = a[i]
		i -= 1
	print(r)


import sys
input = sys.stdin.buffer.readline

def print(val):
	sys.stdout.write(str(val) + '\n')

def prog():
	for _ in range(int(input())):
		n = int(input())
		a = list(map(int, input().split()))
		b = [a[0]]
		for i in range(1, n):
			if a[i] != a[i - 1]:
				b.append(a[i])
		b = [-1] + b + [10 ** 10]
		ans = 0
		peak = 0
		trough = 0
		for i in range(1, len(b) - 1):
			if b[i - 1] < b[i] > b[i + 1]:
				peak = b[i]
			elif b[i - 1] > b[i] < b[i + 1]:
				trough = b[i]
				ans += peak - trough
		print(ans)
prog()


for _ in range(int(input())):
	n = int(input())
	l = [int(x) for x in input().split()]
	s = 0
	for i in range(1, n):
		if l[i] < l[i - 1]:
			s += l[i - 1] - l[i]
	print(s)


import sys

def answer(n, a):
	cnt = 0
	for i in range(1, n):
		if a[i] - a[i - 1] < 0:
			cnt += a[i - 1] - a[i]
	return cnt

def main():
	t = int(input())
	while t:
		n = int(input())
		a = [int(i) for i in sys.stdin.readline().split()]
		print(answer(n, a))
		t -= 1
	return
main()


import sys, math, cmath, time
start_time = time.time()

def solve():
	n = inp()
	a = inlt()
	q = 0
	for i in range(n - 1):
		q = q + max(0, a[i] - a[i + 1])
	print(q)

def main():
	global tt
	if not ONLINE_JUDGE:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	t = 1
	t = inp()
	for tt in range(t):
		solve()
	if not ONLINE_JUDGE:
		print('Time Elapsed :', time.time() - start_time, 'seconds')
		sys.stdout.close()

def inp():
	return int(input())

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

def insr():
	return input().strip()

def invr():
	return map(int, input().split())

def counter(a):
	q = [0] * max(a)
	for i in range(len(a)):
		q[a[i] - 1] = q[a[i] - 1] + 1
	return q

def counter_elements(a):
	q = dict()
	for i in range(len(a)):
		if a[i] not in q:
			q[a[i]] = 0
		q[a[i]] = q[a[i]] + 1
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1
	return q

def factors(n):
	q = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			q.append(i)
			q.append(n // i)
	return list(sorted(list(set(q))))

def prime_factors(n):
	q = []
	while n % 2 == 0:
		q.append(2)
		n = n // 2
	for i in range(3, int(n ** 0.5) + 1, 2):
		while n % i == 0:
			q.append(i)
			n = n // i
	if n > 2:
		q.append(n)
	return list(sorted(q))

def transpose(a):
	(n, m) = (len(a), len(a[0]))
	b = [[0] * n for i in range(m)]
	for i in range(m):
		for j in range(n):
			b[i][j] = a[j][i]
	return b

def factorial(n, m=1000000007):
	q = 1
	for i in range(n):
		q = q * (i + 1) % m
	return q
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
	input = sys.stdin.readline
main()


t = int(input())
for case in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	counter = 0
	for i in range(n - 1):
		if a[n - 1 - i] < a[n - 2 - i]:
			counter += a[n - 2 - i] - a[n - 1 - i]
	print(counter)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	cost = 0
	cur_max = 0
	for x in a:
		if x + cost < cur_max:
			cost += cur_max - (x + cost)
		cur_max = max(cur_max, x + cost)
	print(cost)


from sys import stdin
input = lambda : stdin.readline().strip()
from collections import deque as d
import math
l = len
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	c = 0
	maxtill = -1
	mintill = -1
	step = 0
	for i in range(n - 1):
		if a[i] > a[i + 1] and step == 0:
			maxtill = a[i]
			step += 1
		if step > 0 and (a[i] <= a[i + 1] or i == n - 1):
			mintill = a[i]
			step = 0
		elif step > 0 and i + 1 == n - 1:
			mintill = a[i + 1]
		if maxtill >= 0 and mintill >= 0:
			c += maxtill - mintill
			maxtill = -1
			mintill = -1
	print(c)


for _ in range(int(input())):
	N = int(input())
	List = [int(x) for x in input().split()]
	Ans = 0
	for i in range(N - 1, 0, -1):
		Ans += max(0, List[i - 1] - List[i])
	print(Ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = [a[0]]
	for x in a[1:]:
		b += (max(b[-1], x),)
	c = [b[i] - a[i] for i in range(n)]
	d = [[]]
	for x in c:
		if x:
			d[-1] += (x,)
		elif len(d[-1]) != 0:
			d += ([],)
	ans = 0
	for x in d:
		if len(x):
			ans += x[0]
			mn = x[0]
			for i in range(1, len(x)):
				if x[i] > x[i - 1]:
					ans += x[i] - mn
					mn = x[i]
				mn = min(x[i], mn)
	print(ans)


def answer(n, A):
	count = 0
	for i in range(1, n):
		if A[i] < A[i - 1]:
			count += -A[i] + A[i - 1]
	return count
t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	print(answer(n, arr))


from math import *
from collections import *
from random import *
from decimal import Decimal
from heapq import *
from bisect import *
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 5)

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

def ma():
	return map(int, input().split())

def inp():
	return int(input())

def st1():
	return input().rstrip('\n')
t = inp()
while t:
	t -= 1
	n = inp()
	a = lis()
	loc = a[0]
	fl = 0
	re = 0
	ma = -1
	mi = float('inf')
	i = 1
	while i < n:
		if a[i] < a[i - 1]:
			if i == n - 1:
				if fl == 0:
					re += a[i - 1] - a[i]
				else:
					re += ma - a[i]
			elif fl == 0:
				fl = 1
				mi = a[i]
				ma = a[i - 1]
			else:
				mi = a[i]
		elif fl:
			re += ma - mi
			ma = -1
			mi = float('inf')
			fl = 0
		else:
			pass
		i += 1
	print(re)


test = int(input())
while test:
	test -= 1
	n = int(input())
	a = list(map(int, input().split()))[:n]
	ans = 0
	i = 0
	j = 0
	while i < n:
		i += 1
		if i < n and a[i - 1] > a[i]:
			j = i
			while j < n and a[j - 1] > a[j] and (a[i - 1] > a[j]):
				j += 1
			ans += a[i - 1] - min(a[i:j + 1])
		if j > i:
			i = j
	print(ans)


for _ in [0] * int(input()):
	n = int(input())
	a = [int(x) for x in input().split()]
	count = 0
	p = 0
	p1 = a[0]
	p2 = 0
	p3 = 0
	for i in range(1, n):
		if p == 0:
			if a[i] >= p1:
				p1 = a[i]
			else:
				p2 = a[i]
				p = 1
		elif p == 1:
			if a[i] <= p2:
				p2 = a[i]
			elif a[i] >= p1:
				count += p1 - p2
				p1 = a[i]
				p = 0
			else:
				p3 = a[i]
				p = 2
		elif p == 2:
			if a[i] >= p1:
				count += p1 - p2
				p1 = a[i]
				p = 0
			elif a[i] >= p3:
				p3 = a[i]
			else:
				count += p3 - p2
				p2 = a[i]
				p = 1
	if p != 0:
		count += p1 - p2
	print(count)


t = int(input())
myList = []
for _ in range(t):
	l = 0
	n = int(input())
	a = list(map(int, input().split()))
	for i in range(n - 1):
		l += max(0, a[i] - a[i + 1])
	myList.append(l)
for elem in myList:
	print(elem)


from collections import deque
from math import *
import heapq
from random import *
import sys
from copy import deepcopy
t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	c = 0
	for j in range(len(l) - 1, 0, -1):
		if l[j - 1] > l[j]:
			c += l[j - 1] - l[j]
	print(c)


from sys import stdin, stdout, setrecursionlimit
from math import gcd, ceil, sqrt
from collections import Counter, deque
from bisect import bisect_left, bisect_right
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()
setrecursionlimit(100000)
mod = 1000000007
tc = ii1()
for _ in range(tc):
	n = ii1()
	arr = iia()
	res = 0
	for i in range(1, n):
		if arr[i] + res < arr[i - 1] + res:
			res += arr[i - 1] - arr[i]
	print(res)


from os import path
import sys
from heapq import heappush, heappop
from functools import cmp_to_key as ctk
from collections import deque, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

def ii():
	return int(input())

def si():
	return input().rstrip()

def mi():
	return map(int, input().split())

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def bo(i):
	return ord(i) - ord('a')
file = 1

def f(x):
	n = len(x)
	s = 0
	if n == 1:
		return 0
	mx = x[n - 1]
	for i in range(n - 2, -1, -1):
		if x[i] >= mx:
			s += x[i] - mx
			mx = x[i]
			continue
		if x[i] < x[i + 1]:
			s += abs(x[i] - x[i + 1])
	return s

def solve():
	for _ in range(ii()):
		n = ii()
		a = li()
		mx = a[0]
		x = [a[0]]
		p = []
		f1 = 0
		for i in range(1, n):
			if a[i] <= mx:
				x.append(a[i])
				f1 = 1
			else:
				p.append(x)
				x = [a[i]]
				mx = a[i]
				f1 = 0
		if f1:
			p.append(x)
		ans = 0
		for i in p:
			ans += f(i)
		print(ans)
if file:
	if path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	else:
		input = sys.stdin.readline
solve()


lines = int(input())
for a in range(lines):
	counter = 0
	b = int(input())
	lista = list(map(int, input().split()))
	for i in range(b - 1):
		if lista[i] > lista[i + 1]:
			counter += lista[i] - lista[i + 1]
	print(counter)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	curMax = a[0]
	last = curMax
	ans = []
	curAns = 0
	for i in a:
		if i >= last:
			last = i
			continue
		if i < last:
			curAns += last - i
			last = i
	print(curAns)


from sys import stdin, stdout
test = int(stdin.readline())
for _ in range(test):
	n = int(stdin.readline())
	a = [int(x) for x in stdin.readline().split()]
	ans = 0
	for i in range(1, n):
		if a[i] < a[i - 1]:
			ans += a[i - 1] - a[i]
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	M = [A[0]]
	for a in A[1:]:
		M.append(max(M[-1], a))
	A.append(M[-1])
	ANS = 0
	for i in range(n):
		if A[i] > A[i + 1]:
			continue
		else:
			ANS += min(M[i], A[i + 1]) - A[i]
	print(ANS)


import sys
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	mx = -1
	mi = sys.maxsize
	cost = 0
	for i in range(1, n):
		if a[i - 1] > a[i]:
			mx = max(mx, a[i - 1])
			mi = min(mi, a[i])
		else:
			if mx != -1 and mi != sys.maxsize:
				cost += abs(mx - mi)
			mx = -1
			mi = sys.maxsize
	if mx != -1 and mi != sys.maxsize:
		cost += abs(mx - mi)
	print(cost)


import os
import sys
import math
import heapq
from decimal import *
from io import BytesIO, IOBase
from collections import defaultdict, deque

def r():
	return int(input())

def rm():
	return map(int, input().split())

def rl():
	return list(map(int, input().split()))
for _ in range(r()):
	n = r()
	a = rl()
	ans = True
	for i in range(n - 1):
		if a[i] > a[i + 1]:
			ans = False
			break
	if ans:
		print(0)
	else:
		for i in range(n - 1, 0, -1):
			if a[i - 1] <= a[i]:
				continue
			ans += a[i - 1] - a[i]
		print(ans)


from sys import stdin, gettrace
if gettrace():
	inputi = input
else:

	def input():
		return next(stdin)[:-1]

	def inputi():
		return stdin.buffer.readline()

def solve():
	n = int(inputi())
	aa = [int(a) for a in inputi().split()]
	res = 0
	for (a, b) in zip(aa, aa[1:]):
		res += max(0, a - b)
	print(res)

def main():
	t = int(inputi())
	for _ in range(t):
		solve()
main()


for _ in range(int(input())):
	n = int(input())
	l = [int(i) for i in input().split()][:n]
	cnt = 0
	for i in range(1, n):
		cnt += max(l[i - 1] - l[i], 0)
	print(cnt)


def mp():
	return map(int, input().split())

def it():
	return int(input())
for _ in range(it()):
	n = it()
	l = list(mp())
	ans = 0
	k = 1
	for i in range(n - 1):
		if l[i] > l[i + 1]:
			ans += abs(l[i + 1] - l[i])
			k += 1
	print(ans)


import sys

def input():
	return sys.stdin.readline().rstrip()

def input_split():
	return [int(i) for i in input().split()]
testCases = int(input())
answers = []
for _ in range(testCases):
	n = int(input())
	arr = input_split()
	ans = 0
	for i in range(n - 1):
		if arr[i] > arr[i + 1]:
			ans += arr[i] - arr[i + 1]
	answers.append(ans)
print(*answers, sep='\n')


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(t,) = I()
for _ in range(t):
	(n,) = I()
	l = I()
	an = 0
	mx = l[0]
	ar = [mx]
	cr = 0
	i = 1
	while i < n:
		if l[i] < mx:
			a1 = b1 = l[i]
			i += 1
			while i < n and l[i] < mx:
				if l[i] >= a1:
					cr += l[i] - a1
					a1 = l[i]
				elif l[i - 1] > l[i]:
					cr += l[i - 1] - l[i]
				i += 1
			cr += mx - a1
		else:
			an += cr
			cr = 0
			mx = l[i]
			i += 1
		ar.append(mx)
	an += cr
	print(an)


def solve(n, seq):
	lowerPoints = [0] * n
	index = 1
	lowerPoints_index = 0
	ans = 0
	while index < n:
		if seq[index] < seq[index - 1]:
			lowerPoints[lowerPoints_index] = index
			lowerPoints_index += 1
		index += 1
	lowerPoints.reverse()
	for x in lowerPoints:
		if x == 0:
			continue
		ans += seq[x - 1] - seq[x]
	return ans
for x in range(int(input())):
	n = int(input())
	seq = list(map(int, input().split()))
	print(solve(n, seq))


import sys
import os
import math
import copy
from math import gcd
from bisect import bisect
from io import BytesIO, IOBase
from math import sqrt, floor, factorial, gcd, log, ceil
from collections import deque, Counter, defaultdict
from itertools import permutations, combinations
import itertools

def Int():
	return int(sys.stdin.readline())

def Mint():
	return map(int, sys.stdin.readline().split())

def Lstr():
	return list(sys.stdin.readline().strip())

def Str():
	return sys.stdin.readline().strip()

def Mstr():
	return map(str, sys.stdin.readline().strip().split())

def List():
	return list(map(int, sys.stdin.readline().split()))

def Hash():
	return dict()

def Mod():
	return 1000000007

def Ncr(n, r, p):
	return fact[n] * (ifact[r] * ifact[n - r] % p) % p

def Most_frequent(list):
	return max(set(list), key=list.count)

def Mat2x2(n):
	return [List() for _ in range(n)]

def Lcm(x, y):
	return x * y // gcd(x, y)

def dtob(n):
	return bin(n).replace('0b', '')

def btod(n):
	return int(n, 2)

def common(l1, l2):
	return set(l1).intersection(l2)

def solution():
	for i in range(Int()):
		n = Int()
		a = List()
		res = 0
		for i in range(n - 1):
			res = res + max(a[i] - a[i + 1], 0)
		print(res)
solution()


T = int(input())
while T:
	T -= 1
	N = int(input())
	A = list(map(int, input().split()))
	op = 0
	for i in range(0, N - 1):
		if A[i] > A[i + 1]:
			op += A[i] - A[i + 1]
	print(op)


from sys import stdin, stdout
import heapq
import cProfile
from collections import Counter, defaultdict, deque
from functools import reduce
import math

def get_int():
	return int(stdin.readline().strip())

def get_tuple():
	return map(int, stdin.readline().split())

def get_list():
	return list(map(int, stdin.readline().split()))

def solve():
	n = get_int()
	ls = get_list()
	req = [0]
	maxi = ls[0]
	for i in range(1, n):
		maxi = max(maxi, ls[i])
		diff = max(0, maxi - ls[i])
		req.append(diff)
	ans = 0
	for i in range(1, n):
		if req[i] >= req[i - 1]:
			ans += req[i] - req[i - 1]
	print(ans)

def main():
	solve()
TestCases = True
if TestCases:
	for i in range(get_int()):
		main()
else:
	main()


from fractions import Fraction
import bisect
import os
import io
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
from queue import Queue

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def tinput():
	return input().split()

def rinput():
	return map(int, tinput())

def rlinput():
	return list(rinput())
mod = int(1000000000.0) + 7

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
t = 1
t = iinput()
for _ in range(t):
	n = iinput()
	a = rlinput()
	ans = 0
	i = 1
	while i < n:
		while i < n and a[i] >= a[i - 1]:
			i += 1
		while i < n and a[i] < a[i - 1]:
			ans += a[i - 1] - a[i]
			i += 1
	print(ans)


for _ in range(int(input())):
	n = int(input())
	arr = [int(c) for c in input().split()]
	val = 0
	ans = 0
	for i in range(1, len(arr)):
		arr[i] += val
		if arr[i] >= arr[i - 1]:
			continue
		else:
			diff = arr[i - 1] - arr[i]
			val += diff
			ans += diff
			arr[i] += diff
	print(ans)


import sys, os
cases = int(sys.stdin.readline())
for x in range(cases):
	size = int(sys.stdin.readline()[:-1])
	arr = sys.stdin.readline()[:-1].split(' ')
	arr = [int(c) for c in arr]
	moves = 0
	start = [0] * size
	prev = [0] * size
	for c in range(1, len(arr)):
		if arr[c] < arr[0]:
			start[c] = arr[0] - arr[c]
		if arr[c] < arr[c - 1]:
			prev[c] = arr[c - 1] - arr[c]
		moves += prev[c]
	print(moves)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	b = list(map(int, input().split()))
	ans = 0
	pre = []
	mx = -1
	for i in range(n):
		mx = max(mx, b[i])
		pre.append(mx)
	for i in range(n):
		if b[i] < pre[i]:
			if b[i] < b[i - 1]:
				ans += b[i - 1] - b[i]
	print(ans)


import sys
input = sys.stdin.readline

def main(n, lst):
	i = 1
	cnt = 0
	while i < n:
		if lst[i] < lst[i - 1]:
			j = i
			for j in range(i, n - 1):
				if lst[j] > lst[j + 1]:
					break
				if lst[j + 1] >= lst[i - 1]:
					break
			cnt += lst[i - 1] - lst[i]
			i = j + 1
		else:
			i += 1
	return cnt
for _ in range(int(input())):
	n = int(input())
	lst = list(map(int, input().split()))
	print(main(n, lst))


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(lambda x: int(x), input().split()))
	maximum = a[0]
	i = 1
	total = 0
	while i < len(a):
		j = i
		s = []
		flag = 0
		if a[i] > maximum:
			maximum = a[i]
		while j < len(a) and a[j] < maximum:
			if len(s) == 0:
				s.append(a[j])
			elif s[-1] < a[j]:
				total += a[j] - s[-1]
				s[-1] = a[j]
			else:
				s.append(a[j])
			flag = 1
			j += 1
		if len(s) > 0:
			total += maximum - s[-1]
		if flag == 1:
			i = j
		else:
			i += 1
		if i < len(a):
			if a[i] > maximum:
				maximum = a[i]
	print(total)


t = int(input())
for _ in range(t):
	n = int(input())
	L = list(map(int, input().split()))
	c = d = 0
	m = a = L[0]
	for i in L[1:]:
		if i > m:
			m = i
			a = i
		elif i <= a:
			c = c + a - i
			a = i
		else:
			a = i
			m = i
	print(c)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	count = 0
	for i in range(1, n):
		if a[i] >= a[i - 1]:
			continue
		count += max(0, a[i - 1] - a[i])
	print(count)


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


def f(arr):
	d = max(arr)
	for i in range(len(arr)):
		arr[i] = d - arr[i]
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	i = n - 1
	ans = 0
	while i > 0:
		if arr[i - 1] <= arr[i]:
			i -= 1
			continue
		ans += arr[i - 1] - arr[i]
		i -= 1
	print(ans)


import sys
input = sys.stdin.readline
(T,) = map(int, input().split())
for _ in range(T):
	(N,) = map(int, input().split())
	X = list(map(int, input().split()))
	X = X[::-1]
	R = 0
	for i in range(N - 1):
		if X[i] < X[i + 1]:
			R += X[i + 1] - X[i]
	print(R)


def main():
	for _ in range(int(input())):
		n = int(input())
		a = list(map(int, input().split()))
		count = 0
		for i in range(n - 1, 0, -1):
			if a[i] >= a[i - 1]:
				continue
			count += abs(a[i] - a[i - 1])
		print(count)
main()


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from collections import Counter
from collections import deque
from heapq import heappush, heappop, heapify
mod = int(1000000000.0) + 7
ip = lambda : int(stdin.readline())
inp = lambda : map(int, stdin.readline().split())
ips = lambda : stdin.readline().rstrip()
t = ip()
for _ in range(t):
	n = ip()
	arr = list(inp())
	ans = 0
	for i in range(n - 1):
		ans += max(arr[i] - arr[i + 1], 0)
	print(ans)


for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	cou = 0
	for i in range(n - 1, 0, -1):
		if lis[i] < lis[i - 1]:
			cou += lis[i - 1] - lis[i]
	print(cou)


from collections import Counter
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	i = n - 1
	moves = 0
	while i:
		if arr[i] < arr[i - 1]:
			moves += abs(arr[i] - arr[i - 1])
		i -= 1
	print(moves)


for i1 in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	atleast = max(l)
	ans = 0
	i = n - 1
	min = 10000000
	while i > 0:
		if l[i - 1] <= l[i]:
			min = l[i - 1]
		else:
			if i == n - 1:
				min = l[n - 1]
			ans += l[i - 1] - min
			min = l[i - 1]
		i -= 1
	print(ans)


import sys

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math
from collections import defaultdict
for _ in range(ri()):
	n = ri()
	l = ria()
	cnt = 0
	for i in range(n - 1):
		cnt += max(0, l[i] - l[i + 1])
	wi(cnt)


t = int(input())
for you in range(t):
	n = int(input())
	l = input().split()
	li = [int(i) for i in l]
	curr = 0
	for i in range(1, n):
		if li[i] < li[i - 1]:
			curr = curr + (li[i - 1] - li[i])
	print(curr)


def steps_non_decreasing(array):
	sum = 0
	for index in range(1, len(array)):
		diff = array[index] - array[index - 1]
		if diff < 0:
			sum = sum - diff
	return sum
total = int(input())
for index in range(2 * total):
	line = input()
	if index % 2 == 0:
		pass
	else:
		array = [int(x) for x in line.split(' ')]
		steps = steps_non_decreasing(array)
		print(steps)


def solve(l, n):
	c = 0
	k = 0
	for i in range(1, n):
		l[i] += c
		if l[i] < l[i - 1]:
			k += l[i - 1] - l[i]
			c += l[i - 1] - l[i]
			l[i] = l[i - 1]
	print(k)
t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	solve(l, n)


from sys import stdin, stdout, setrecursionlimit

class Tail_Recursion_Optimization:

	def __init__(self, RECURSION_LIMIT, STACK_SIZE):
		setrecursionlimit(RECURSION_LIMIT)
		threading.stack_size(STACK_SIZE)
		return None

class SOLVE:

	def solve(self):
		R = stdin.readline
		W = stdout.write
		ans = []
		for i in range(int(R())):
			n = int(R())
			a = [int(x) for x in R().split()]
			(cnt, mn) = (0, a[n - 1])
			for j in range(n - 2, -1, -1):
				if a[j] > mn:
					cnt += a[j] - mn
				mn = a[j]
			ans.append(str(cnt))
		W('\n'.join(ans))
		return 0

def main():
	s = SOLVE()
	s.solve()
main()


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	if n == 1:
		print(0)
		continue
	l.append(1000000001)
	ans = 0
	mx = l[0]
	temp = 0
	for i in range(1, n):
		if l[i - 1] > l[i]:
			ans += l[i - 1] - l[i]
	print(ans)


def main():
	t = int(input())
	while t > 0:
		t -= 1
		soln()

def soln():
	n = int(input())
	a = list(map(int, input().split(' ')))
	cnt = 0
	i = n - 1
	while i > 0:
		if a[i] >= a[i - 1]:
			i -= 1
		else:
			dif = a[i - 1] - a[i]
			cnt += dif
			i -= 1
	print(cnt)
main()


t = int(input())
ans = []
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	(idx, count) = (1, 0)
	while idx < n:
		while idx < n and arr[idx] >= arr[idx - 1]:
			idx += 1
		ref = arr[idx - 1]
		while idx < n and arr[idx] <= arr[idx - 1]:
			idx += 1
		count += ref - arr[idx - 1]
	ans.append(count)
for x in ans:
	print(x)


import sys
pprint = lambda s: print(' '.join(map(lambda x: str(x), s)))
input = lambda : sys.stdin.readline().strip()
ipnut = input
for i in range(int(input())):
	n = int(input())
	ans = 0
	a = list(map(int, input().split()))
	for i in range(n - 1):
		ans += max(0, a[i] - a[i + 1])
	print(ans)


t = int(input())
for aa in range(t):
	n = int(input())
	a = [int(xx) for xx in input().split()]
	r = 0
	a1 = a[0]
	for i in range(n - 1):
		a2 = a[i + 1]
		if a1 > a2:
			r += a1 - a2
		a1 = a2
	print(r)