Your algorithms have become so good at predicting the market that you now know what the share price of Wooden Orange Toothpicks Inc. (WOT) will be for the next number of days.

Each day, you can either buy one share of WOT, sell any number of shares of WOT that you own, or not make any transaction at all. What is the maximum profit you can obtain with an optimum trading strategy?

Example 

$prices=[1,2]$  

Buy one share day one, and sell it day two for a profit of $1$. Return $1$. 

$prices=[2,1]$   

No profit can be made so you do not buy or sell stock those days. Return $0$.

Function Description  

Complete the stockmax function in the editor below.  

stockmax has the following parameter(s):  

prices: an array of integers that represent predicted daily stock prices    

Returns   

int:  the maximum profit achievable

Input Format

The first line contains the number of test cases $t$.

Each of the next $t$ pairs of lines contain: 

- The first line contains an integer $n$, the number of predicted prices for WOT. 

- The next line contains n space-separated integers $prices [i]$, each a predicted stock price for day $i$.  

Constraints

$1\leq t\leq10$  
$1\le n\le50000$
$1\leq prices[i]\leq10000$

Output Format

Output $t$ lines, each containing the maximum profit which can be obtained for the corresponding test case.

Sample Input
STDIN       Function
-----       --------
3           q = 3
3           prices[] size n = 3
5 3 2       prices = [5, 3, 2]
3           prices[] size n = 3
1 2 100     prices = [1, 2, 100]
4           prices[] size n = 4
1 3 1 2     prices =[1, 3, 1, 2]

Sample Output
0
197
3

Explanation

For the first case, there is no profit because the share price never rises, return $0$. 

For the second case, buy one share on the first two days and sell both of them on the third day for a profit of $197$. 

For the third case, buy one share on day 1, sell one on day 2, buy one share on day 3, and sell one share on day 4.  The overall profit is $3$.

Difficulty: MEDIUM
Tags: Dynamic programming
Skill types: Dynamic programming

Starter code:

Solutions:
test = int(input())
for i in range(test):
	n = int(input())
	a = list(map(int, input().split()))
	c = 0
	i = len(a) - 1
	while i >= 0:
		d = a[i]
		l = i
		p = 0
		while a[i] <= d and i >= 0:
			p += a[i]
			i -= 1
		c += (l - i) * a[l] - p
		continue
	print(c)


for i in range(int(input())):
	n = int(input())
	val = 0
	maxp = 0
	for p in reversed([int(x) for x in input().split()]):
		val += max(0, maxp - p)
		maxp = max(p, maxp)
	print(val)


def f(A):
	li = [0]
	for i in range(1, len(A)):
		for _ in range(len(li) - 1, -1, -1):
			if A[li[-1]] <= A[i]:
				li.pop()
			else:
				li.append(i)
				break
		else:
			li.append(i)
	res = 0
	for i in range(li[0]):
		res += A[li[0]] - A[i]
	for i in range(1, len(li)):
		for j in range(li[i - 1] + 1, li[i]):
			res += A[li[i]] - A[j]
	return res
for _ in range(int(input())):
	input()
	print(f([int(i) for i in input().split()]))


def hasBigger(prices, price_index, next_biggest_index):
	for i in range(price_index, len(prices)):
		if prices[i] > prices[price_index]:
			next_biggest_index[0] = i
			return True
	return False
T = int(input())
for testCase in range(T):
	N = int(input())
	prices = input().split()
	prices = list(map(int, prices))
	shares = 0
	profit = 0
	next_biggest_index = [0]
	for i in range(len(prices)):
		if hasBigger(prices, i, next_biggest_index):
			shares += 1
			profit -= prices[i]
		else:
			profit += shares * prices[i]
			shares = 0
	print(profit)


def calc_profit(prices):
	next_price = 0
	profit = 0
	for price in reversed(prices):
		if next_price > price:
			profit += next_price - price
		elif next_price < price:
			next_price = price
	return profit
tests = int(input())
for i in range(tests):
	input()
	price_list = list(map(int, input().split()))
	print(calc_profit(price_list))


def calc(ns):
	total = 0
	high = ns.pop()
	while len(ns):
		price = ns.pop()
		if price <= high:
			total += high - price
		else:
			high = price
	return total

def main():
	T = int(input())
	for _ in range(T):
		input()
		ns = list(map(int, input().split()))
		print(calc(ns))
main()


T = int(input())
for _ in range(T):
	input()
	A = list(map(int, input().split()))
	vBuy = len(A) * [False]
	maxVal = 0
	for i in range(len(A) - 1, -1, -1):
		maxVal = max(maxVal, A[i])
		if A[i] < maxVal:
			vBuy[i] = True
	totBuy = 0
	nbBuy = 0
	totSell = 0
	for i in range(len(A)):
		if vBuy[i]:
			totBuy += A[i]
			nbBuy += 1
		else:
			totSell += nbBuy * A[i]
			nbBuy = 0
	print(totSell - totBuy)


import sys
cases = int(input())
for case in range(0, cases):
	n = int(input())
	prices = list(map(int, input().split()))
	profit = 0
	current_max = prices[-1]
	for i in range(len(prices) - 1, -1, -1):
		if prices[i] >= current_max:
			current_max = prices[i]
		profit += current_max - prices[i]
	print(profit)


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


testcases = int(input())

def find_max_day(prices):
	(mday, mprice) = (0, 0)
	for day in range(len(prices)):
		if prices[day] > mprice:
			(mday, mprice) = (day, prices[day])
	return mday

def max_profit(prices):
	if len(prices) == 0:
		return 0
	sell_day = find_max_day(prices)
	sell_price = prices[sell_day]
	profit = 0
	for i in range(sell_day):
		profit += sell_price - prices[i]
	return profit + max_profit(prices[sell_day + 1:])
for _ in range(testcases):
	days = int(input())
	prices = list(map(int, input().split()))
	print(max_profit(prices))


T = int(input())
while T > 0:
	N = int(input())
	a = [int(i) for i in input().split(' ')]
	p = N - 1
	(curSum, curMax) = (0, a[N - 1])
	while p >= 0:
		if a[p] > curMax:
			curMax = a[p]
		curSum += curMax - a[p]
		p -= 1
	print(curSum)
	T -= 1


def profitCalc(pricesList, profits):
	tempProfits = 0
	maxPrice = max(pricesList)
	maxPriceIndex = pricesList.index(maxPrice)
	if maxPriceIndex == len(pricesList) - 1:
		i = 0
		for i in range(maxPriceIndex):
			tempProfits = tempProfits + (maxPrice - pricesList[i])
	else:
		firstList = pricesList[0:maxPriceIndex + 1]
		tempProfits = tempProfits + profitCalc(firstList, tempProfits)
		secondList = pricesList[maxPriceIndex + 1:len(pricesList) + 1]
		tempProfits = tempProfits + profitCalc(secondList, tempProfits)
	return tempProfits
numTestCases = int(input())
answer = []
for i in range(numTestCases):
	numDays = int(input())
	prices = [int(i) for i in input().strip().split()]
	answer.append(profitCalc(prices, 0))
for i in answer:
	print(i)


def findmax(arr, l):
	(maxi, ind) = (0, -1)
	for i in range(l, len(arr)):
		if arr[i] > maxi:
			maxi = arr[i]
			ind = i
	return ind
t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().strip('\n').split(' ')))
	l = 0
	ind = findmax(arr, l)
	cost = 0
	while True:
		share = 0
		for i in range(l, ind):
			cost -= arr[i]
			share += 1
		cost += share * arr[ind]
		if ind == len(arr) - 1:
			break
		l = ind + 1
		ind = findmax(arr, l)
	print(cost)


t1 = input('')
t = int(t1)
for i in range(0, t):
	n1 = input('')
	n = int(n1)
	k1 = input('')
	a1 = k1.split()
	maxi = []
	a = []
	for j in range(0, n):
		a.append(int(a1[j]))
		maxi.append(a[j])
	j = n - 2
	while j >= 0:
		maxi[j] = max(maxi[j + 1], a[j])
		j = j - 1
	avail = 0
	profit = 0
	for j in range(0, n):
		if a[j] < maxi[j]:
			avail = avail + 1
			profit = profit - a[j]
		if a[j] == maxi[j]:
			profit = profit + avail * a[j]
			avail = 0
	print(profit)


import heapq

class PriorityQueue:

	def __init__(self, data=None):
		self.counter = 0
		self.heap = []
		if data is not None:
			self._heapify(data)

	def _heapify(self, data):
		for value in data:
			self.heap.append((-1 * value[1], self.counter, value))
			self.counter += 1
		heapq.heapify(self.heap)

	def push(self, priority, value):
		heapq.heappush(self.heap, (priority, self.counter, value))
		self.counter += 1

	def peek(self):
		try:
			return self.heap[0][2]
		except IndexError:
			return (float('inf'), 0)

	def pop(self):
		return heapq.heappop(self.heap)[2]

	def __repr__(self):
		return '<PriorityQueue heap={!r}>'.format(self.heap)

def max_profit(prices):
	pq = PriorityQueue(enumerate(prices))
	profit = 0
	stocks = 0
	for (i, price) in enumerate(prices):
		while True:
			(li, lmax) = pq.peek()
			if i > li:
				pq.pop()
			else:
				break
		if i < li and price < lmax:
			profit -= price
			stocks += 1
		if i == li:
			profit += price * stocks
			stocks = 0
	return profit

def main():
	n = int(input().strip())
	prices = list(map(int, input().strip().split(' ')))
	assert n == len(prices)
	print(max_profit(prices))
count = int(input().strip())
for i in range(count):
	main()


__author__ = 'jonghewk'

def profit(Stocks):
	max = 0
	StockBuy = [1] * len(Stocks)
	money = 0
	for i in range(len(Stocks) - 1, -1, -1):
		s = Stocks[i]
		if max <= s:
			max = s
			StockBuy[i] = 0
		money += max - s
	print(money)
nCase = int(input())
Stock = []
for i in range(nCase):
	N = int(input())
	stock = [int(j) for j in input().split()]
	Stock.append(stock)
for i in range(len(Stock)):
	profit(Stock[i])


import sys
T = int(sys.stdin.readline())
for i in range(T):
	N = int(sys.stdin.readline())
	prices = list(map(int, sys.stdin.readline().split()))
	change = prices[:]
	for i in reversed(range(N - 1)):
		change[i] = max(prices[i], change[i + 1])
	print(sum((max(0, change[i] - prices[i]) for i in range(N))))


count = int(input())
for i in range(count):
	size = int(input())
	prices = [int(entry) for entry in input().strip().split()]
	strategy = [0]
	max_from_end = prices[size - 1]
	for i in range(1, size):
		current_price = prices[size - i - 1]
		if current_price > max_from_end:
			max_from_end = current_price
			strategy.insert(0, 0)
		else:
			strategy.insert(0, 1)
	current_stock_size = 0
	max_profit = 0
	for i in range(size):
		if strategy[i] == 0:
			max_profit += current_stock_size * prices[i]
			current_stock_size = 0
		else:
			current_stock_size += 1
			max_profit -= prices[i]
	print(max_profit)


def main():
	num_cases = int(input())
	for i in range(num_cases):
		num_prices = int(input())
		prices = list(map(int, input().split()))
		print(max_profit(prices, num_prices))

def max_profit(prices, num_prices):
	profit = 0
	max_price = -1
	for i in range(num_prices - 1, -1, -1):
		if prices[i] > max_price:
			max_price = prices[i]
		profit += max_price - prices[i]
	return profit
main()


def calprofit(stockvalues):
	dobuy = [1] * len(stockvalues)
	prof = 0
	m = 0
	for i in range(len(stockvalues) - 1, -1, -1):
		ai = stockvalues[i]
		if m <= ai:
			dobuy[i] = 0
			m = ai
		prof += m - ai
	return prof
numCases = int(input())
for i in range(numCases):
	n = int(input())
	stockvalues = []
	line = input().split()
	for j in range(n):
		stockvalues.append(int(line[j]))
	print(calprofit(stockvalues))


import sys, math
test = int(sys.stdin.readline())

def process(l, a):
	if a == len(l):
		return 0
	maxindex = a
	maxi = int(l[a])
	minindex = a
	mini = int(l[a])
	for i in range(a, len(l)):
		if l[i] > maxi:
			maxi = l[i]
			maxindex = i
	cost = 0
	shares = 0
	for i in range(a, maxindex):
		cost += l[i]
		shares += 1
	return max(shares * maxi - cost, 0) + process(l, maxindex + 1)
for i in range(0, test):
	sys.stdin.readline()
	l = sys.stdin.readline().split(' ')
	y = [int(x) for x in l]
	print(process(y, 0))


T = int(input())
for t in range(T):
	n = int(input())
	a = input().split()
	ar = [int(x) for x in a]
	m = [ar[n - 1]] * n
	for i in range(n - 2, -1, -1):
		m[i] = max(m[i + 1], ar[i])
	pro = 0
	for i in range(n):
		pro += m[i] - ar[i]
	print(pro)


def find_max_profit(ar, n):
	max_pr = [0]
	temp_sum = 0
	sum_count = 0
	local_max = 0
	sum_arr = 0
	for i in range(n - 1):
		if ar[i + 1] >= ar[i]:
			temp_sum += ar[i]
			sum_count += 1
		elif ar[i] > local_max:
			local_max = ar[i]
			max_pr = [0]
			max_pr.append(ar[i] * i - sum_arr)
			sum_count = 0
			temp_sum = 0
		else:
			max_pr.append(ar[i] * sum_count - temp_sum)
			sum_count = 0
			temp_sum = 0
		sum_arr += ar[i]
	if ar[n - 1] >= local_max:
		max_pr = [0]
		max_pr.append(ar[n - 1] * (n - 1) - sum_arr)
	else:
		max_pr.append(ar[n - 1] * sum_count - temp_sum)
	return sum(max_pr)

def find_max_profit2(ar):
	if len(ar) == 0:
		return 0
	m = max(ar)
	n = len(ar)
	for i in range(n):
		if ar[n - 1 - i] == m:
			s = m * (n - i) - sum(ar[:n - i])
			return s + find_max_profit2(ar[n - i:])
t = int(input())
for i in range(t):
	n = int(input())
	raw = input().split()
	ar = [int(i) for i in raw]
	print(find_max_profit2(ar))


def compute(prices):
	if len(prices) == 0:
		return 0
	m = max(prices)
	pos = prices.index(m)
	return m * pos - sum(prices[:pos]) + compute(prices[pos + 1:])
t = int(input())
for i in range(t):
	n = int(input())
	prices = [int(j) for j in input().split()]
	print(compute(prices))


def max1(nums):
	mi = 0
	for i in range(1, len(nums)):
		if nums[i] > nums[mi]:
			mi = i
	return mi
t = int(input())
for i in range(t):
	n = int(input())
	line = input().split()
	nums = [int(line[j]) for j in range(n)]
	total = 0
	startFrom = 0
	maxIndex = 0
	while startFrom < len(nums):
		maxIndex = max1(nums[startFrom:])
		for j in range(startFrom, startFrom + maxIndex):
			total += nums[startFrom + maxIndex] - nums[j]
		startFrom += maxIndex + 1
	print(total)


def profit(prices):
	if len(prices) == 0:
		return 0
	imax = 0
	for i in range(0, len(prices)):
		if prices[i] >= prices[imax]:
			imax = i
	return imax * prices[imax] - sum(prices[0:imax]) + profit(prices[imax + 1:])
T = int(input())
for t in range(0, T):
	N = int(input())
	prices = [int(x) for x in input().split(' ')]
	print(profit(prices))


T = int(input())
for _ in range(T):
	N = int(input())
	S = list(map(int, input().strip().split(' ')))[::-1]
	(M, answer) = (0, 0)
	for i in S:
		M = max(M, i)
		answer += M - i
	print(answer)


def solve(n, prices):
	profit = 0
	m = 0
	for price in reversed(prices):
		if m <= price:
			m = price
		profit += m - price
	return profit
import sys
data = sys.stdin.readlines()
T = int(data[0])
for i in range(1, len(data) - 1, 2):
	N = int(data[i])
	prices = list(map(int, data[i + 1].split()))
	print(solve(N, prices))


def calcMaxes(l):
	output = [0 for i in range(len(l))]
	output[len(l) - 1] = l[len(l) - 1]
	for i in range(len(l) - 2, -1, -1):
		output[i] = max(output[i + 1], l[i])
	return output
t = int(input())
for testNum in range(t):
	length = int(input())
	price = [int(val) for val in input().split()]
	maxes = calcMaxes(price)
	output = [0 for i in range(length)]
	for i in range(length):
		output[i] = max(0, maxes[i] - price[i])
	print(sum(output))


import sys
cases = int(input())
for case in range(0, cases):
	n = int(input())
	prices = list(map(int, input().split()))
	profit = 0
	current_max = prices[-1]
	for i in range(len(prices) - 1, -1, -1):
		if prices[i] >= current_max:
			current_max = prices[i]
		profit += current_max - prices[i]
	print(profit)


testSize = int(input())
while testSize > 0:
	testSize -= 1
	stockSize = int(input())
	stock = list(map(int, input().split()))
	totalReturn = 0
	profit = 0
	while stockSize > 0:
		currentMax = max(stock)
		currentIndex = stock.index(currentMax)
		profit += currentMax * currentIndex - sum(stock[:currentIndex])
		stock = stock[currentIndex + 1:]
		stockSize -= currentIndex + 1
	print(profit)


def stock_maximize2(prices):
	max_so_far = prices[-1]
	profit = 0
	for i in range(len(prices) - 2, -1, -1):
		if max_so_far > prices[i]:
			profit += max_so_far - prices[i]
		else:
			max_so_far = prices[i]
	return profit
T = int(input())
for i in range(T):
	input()
	prices = [int(x) for x in input().split(' ')]
	print(stock_maximize2(prices))


def maximumProfit(k, stock):
	eff = k * [0]
	e = 0
	for i in range(k - 1, -1, -1):
		e = eff[i] = max(e, stock[i])
	n = 0
	c = 0
	p = 0
	for i in range(k):
		if stock[i] < eff[i]:
			n += 1
			c += stock[i]
		elif n > 0:
			p += n * stock[i] - c
			c = 0
			n = 0
	return p
n = int(input())
for i in range(n):
	k = int(input())
	stock = [int(i) for i in input().split()]
	print(maximumProfit(k, stock))


import sys

def max_profit(prices):
	max_price = -99999999999999
	sum_profit = 0
	for p in reversed(prices):
		if p < max_price:
			sum_profit += max_price - p
		elif p > max_price:
			max_price = p
	return sum_profit
lines = int(sys.stdin.readline())
for test_i in range(lines):
	sys.stdin.readline()
	values = list(map(int, sys.stdin.readline().strip().split(' ')))
	print(max_profit(values))


import sys
getline = sys.stdin.readline
write = sys.stdout.write

class rise:

	def __init__(self, days, sale):
		self.days = days
		self.sale = sale
		self.profit = 0

	def escalate(self, newprice):
		self.profit = self.profit + self.days * (newprice - self.sale)
		self.days = self.days + 1
		self.sale = newprice

	def mergeold(self, prevrise):
		self.profit = self.profit + prevrise.profit + prevrise.days * (self.sale - prevrise.sale)
		self.days = self.days + prevrise.days
testcount = int(getline())
for test in range(testcount):
	t = int(getline())
	prices = [int(item) for item in getline().split(' ')]
	stack = []
	cur_rise = rise(0, 0)
	for i in range(len(prices)):
		today_price = prices[i]
		if today_price >= cur_rise.sale:
			cur_rise.escalate(today_price)
			while len(stack) > 0 and stack[-1].sale <= today_price:
				prev = stack.pop()
				cur_rise.mergeold(prev)
		else:
			stack.append(cur_rise)
			cur_rise = rise(1, today_price)
	profit = 0
	stack.append(cur_rise)
	for entry in stack:
		profit = profit + entry.profit
	write(str(profit) + '\n')


def determine_max_profit(prices, profit=0):
	max_price = max(prices)
	for day in range(prices.index(max_price)):
		profit += max_price - prices[day]
	if prices.index(max_price) == len(prices) - 1:
		return profit
	else:
		return determine_max_profit(prices[prices.index(max_price) + 1:], profit)
num_cases = int(input())
for _ in range(num_cases):
	num_days = int(input())
	stock_prices = [int(x) for x in input().split()]
	print(str(determine_max_profit(stock_prices)))


def compute(prices):
	if len(prices) == 0:
		return 0
	m = max(prices)
	pos = prices.index(m)
	return m * pos - sum(prices[:pos]) + compute(prices[pos + 1:])
t = int(input())
for i in range(t):
	n = int(input())
	prices = [int(j) for j in input().split()]
	print(compute(prices))


def calc(prices):
	max_next_price = [0] * len(prices)
	max_next = 0
	for i in reversed(range(len(prices))):
		if prices[i] > max_next:
			max_next = prices[i]
		max_next_price[i] = max_next
	balance = 0
	shares = 0
	for (i, v) in enumerate(prices):
		if max_next_price[i] > v:
			balance -= v
			shares += 1
		elif max_next_price[i] == v:
			balance += shares * v
			shares = 0
		else:
			pass
	return balance

def read_ints():
	return [int(x) for x in input().strip().split()]
T = int(input())
for tc in range(T):
	N = int(input())
	prices = read_ints()
	profit = calc(prices)
	print(profit)


t = int(input())
for i in range(t):
	n = int(input())
	prices = list(map(int, input().split()))
	profit = 0
	j = 0
	while j < n:
		m = max(prices[j:])
		k = prices.index(m, j)
		profit += (k - j) * prices[k] - sum(prices[j:k])
		j = k + 1
	print(profit)


import sys
T = int(sys.stdin.readline().strip(' \t\r\n'))
for t in range(T):
	N = int(sys.stdin.readline().strip(' \t\r\n'))
	prices = [int(x) for x in sys.stdin.readline().strip(' \t\r\n').split(' ')]
	maxv = -1
	max_list = []
	for i in range(1, len(prices) + 1):
		if prices[-i] > maxv:
			maxv = prices[-i]
		max_list.append(maxv)
	max_list = max_list[::-1]
	profit = 0
	for i in range(len(prices)):
		if max_list[i] > prices[i]:
			profit += max_list[i] - prices[i]
	print(profit)


num_test = int(input().strip())
for i in range(num_test):
	profit = 0
	num_vals = int(input().strip())
	nums = list(map(int, input().strip().split(' ')))
	maxLater = [0] * num_vals
	maxLater[num_vals - 1] = nums[num_vals - 1]
	for j in range(len(nums) - 2, -1, -1):
		maxLater[j] = max(nums[j], maxLater[j + 1])
	for j in range(len(nums) - 1):
		temp = maxLater[j] - nums[j]
		if temp > 0:
			profit += temp
	print(profit)


import fileinput
for line in fileinput.input():
	if fileinput.lineno() != 1:
		if fileinput.lineno() % 2:
			prices = [int(x) for x in line.strip().split(' ')]
			prices.reverse()
			total = 0
			peak = prices[0]
			for i in range(1, len(prices)):
				diff = peak - prices[i]
				if diff > 0:
					total += diff
				else:
					peak = prices[i]
			print(total)


T = int(input())
for t in range(T):
	N = int(input())
	price = [int(e) for e in input().split()]
	maxprice = 0
	profit = 0
	for i in range(N - 1, -1, -1):
		if price[i] > maxprice:
			maxprice = price[i]
		else:
			profit += maxprice - price[i]
	print(profit)


import math

def addProfit(arr):
	if len(arr) == 0:
		return 0
	val = max(arr)
	index = arr.index(val)
	returnMoney = index * val
	investedMoney = 0
	for i in range(index):
		investedMoney += arr[i]
	profit = returnMoney - investedMoney
	if index == len(arr):
		return profit
	else:
		return profit + addProfit(arr[index + 1:])
t = int(input())
for i in range(t):
	n = int(input())
	stockVals = [int(i) for i in input().split()]
	profit = addProfit(stockVals)
	print(profit)


def max_profit(prices):
	max_future = [0] * len(prices)
	max_future[len(prices) - 1] = prices[len(prices) - 1]
	for i in range(len(prices) - 2, -1, -1):
		max_future[i] = max_future[i + 1] if max_future[i + 1] > prices[i] else prices[i]
	profit = 0
	for (price, max_price_future) in zip(prices, max_future):
		if price < max_price_future:
			profit += max_price_future - price
	return profit
T = int(input())
for t in range(T):
	N = int(input())
	prices = [int(i) for i in str(input()).split()]
	print(max_profit(prices))


import sys
T = int(sys.stdin.readline().strip())
while T > 0:
	N = int(sys.stdin.readline().strip())
	prices = [int(x) for x in sys.stdin.readline().split()]
	profit = [0 for x in range(len(prices))]
	futuremaxes = [0 for x in range(len(prices))]
	currentmax = 0
	for i in range(len(prices) - 1, -1, -1):
		futuremaxes[i] = 0 if i == len(prices) - 1 else max(prices[i + 1], currentmax)
		if i != len(prices) - 1 and futuremaxes[i] == prices[i + 1]:
			currentmax = prices[i + 1]
	for i in range(len(prices)):
		saleprice = max(futuremaxes[i], prices[i])
		possibleprofit = saleprice - prices[i]
		profit[i] = max(0, possibleprofit)
	print(sum(profit))
	T -= 1


for _ in range(int(input())):
	n = int(input())
	ps = [int(x) for x in input().split()]
	t = 0
	r = 0
	while t < n:
		m = max(ps[t:])
		i = ps[t:].index(m)
		r += m * i
		for p in ps[t:t + i]:
			r -= p
		t += i + 1
	print(r)


testc = int(input())
d = {}
for i in range(1, testc + 1):
	tn_i = int(input())
	tn_li = input()
	tn_lii = tn_li.split()
	li = []
	for j in range(0, tn_i):
		tni_j = int(tn_lii[j])
		li.append(tni_j)
	d[i] = li
for i in range(1, testc + 1):
	di = d[i]
	l_i = []
	for j in range(0, len(di)):
		l_i.append((di[j], j))
	l_i.sort()
	l_i.reverse()
	l1_i = [l_i[0][1]]
	for j in range(1, len(l_i)):
		if l1_i[-1] < l_i[j][1]:
			l1_i.append(l_i[j][1])
	profit = 0
	hold = 0
	for j in range(len(di)):
		if j != l1_i[0]:
			profit -= di[j]
			hold += 1
		else:
			profit += hold * di[j]
			hold = 0
			del l1_i[0]
	print(profit)


t = int(input())
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	maxR = [0] * n
	for i in reversed(range(n - 1)):
		maxR[i] = max(p[i + 1], maxR[i + 1])
	ans = sum((maxR[i] - p[i] for i in range(n - 1) if maxR[i] > p[i]))
	print(ans)


T = int(input())
for i in range(T):
	N = int(input())
	price = [int(x) for x in input().split()]
	decision = [-1 for x in range(N)]
	maxim = price[N - 1]
	for j in range(N - 1, -1, -1):
		if price[j] >= maxim:
			maxim = price[j]
			decision[j] = 1
		else:
			decision[j] = 0
	num_buys = 0
	balance = 0
	for j in range(N):
		if decision[j] == 0:
			balance = balance - price[j]
			num_buys += 1
		else:
			balance = balance + num_buys * price[j]
			num_buys = 0
	print(balance)


def compute(prices):
	if len(prices) == 0:
		return 0
	m = max(prices)
	pos = prices.index(m)
	return m * pos - sum(prices[:pos]) + compute(prices[pos + 1:])
t = int(input())
for i in range(t):
	n = int(input())
	prices = [int(j) for j in input().split()]
	print(compute(prices))


T = int(input())
for t in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	maxs = [0] * n
	maxs[n - 1] = a[n - 1]
	for i in reversed(range(n - 1)):
		if a[i] > maxs[i + 1]:
			maxs[i] = a[i]
		else:
			maxs[i] = maxs[i + 1]
	profit = 0
	for i in range(n):
		profit += max(0, maxs[i] - a[i])
	print(profit)


def stockProfit(prices):
	profit = 0
	if len(prices) <= 1:
		return profit
	sellPrice = -1
	i = len(prices) - 1
	while i >= 0:
		if prices[i] > sellPrice:
			sellPrice = prices[i]
		elif prices[i] < sellPrice:
			profit += sellPrice - prices[i]
		i -= 1
	return profit

def convertToInt(lst):
	output = []
	for i in lst:
		output.append(int(i))
	return output
t = int(input())
assert 1 <= t <= 10
for i in range(t):
	cases = int(input())
	assert 1 <= t <= 50000
	line = input().strip()
	prices = convertToInt(line.split(' '))
	print(stockProfit(prices))


cases = int(input())
for i in range(cases):
	Nshares = int(input())
	shares = [int(x) for x in input().strip().split()]
	shares.reverse()
	profit = 0
	maxsell = 0
	maxsell = shares[0]
	for i in range(1, len(shares)):
		if shares[i] > maxsell:
			maxsell = shares[i]
		else:
			profit += maxsell - shares[i]
	print(profit)


def find_max_profit(price_list):
	profit = 0
	while len(price_list):
		peak = max(price_list)
		peak_index = price_list.index(peak)
		profit += peak_index * peak - sum(price_list[:peak_index])
		price_list = price_list[peak_index + 1:]
	return profit
for case in range(int(input())):
	_ = input()
	print(find_max_profit([int(x) for x in input().split()]))


for i in range(int(input())):
	N = input()
	L = list(map(int, input().split()))
	ans = 0
	c = 0
	while True:
		try:
			z = max(L)
		except:
			break
		for j in L:
			if j == z:
				break
			ans -= j
			c += 1
		ans += c * z
		c = 0
		try:
			L = L[L.index(z) + 1:]
		except:
			break
	print(ans)


def par(l):
	lis = []
	a = max(set(l))
	i = l.index(a)
	lis.append(l[:i + 1])
	lis.append(l[i + 1:])
	return lis

def value(l):
	sum = 0
	for i in range(0, len(l) - 1):
		sum = sum - l[i]
	if len(l) >= 2:
		return sum + (len(l) - 1) * l[len(l) - 1]
	if len(l) == 1:
		return 0

def stock(l, v):
	if l == []:
		print(v)
	if l != []:
		a = par(l)
		stock(a[1], v + value(a[0]))
num = int(input())
lis = []
for i in range(1, num + 1):
	numi = int(input())
	li = [int(x) for x in input().split()]
	lis.append(li)
for s in lis:
	stock(s, 0)


import sys
import math

def partial_search(A):
	s = 0
	p = max(A)
	for i in range(len(A)):
		if A[i] < p:
			s = s + p - A[i]
		else:
			return (s, A[i + 1:])
	return (s, [])
T = int(sys.stdin.readline().strip())
for t in range(T):
	sys.stdin.readline()
	result = 0
	A = list(map(lambda x: int(x.strip()), sys.stdin.readline().split()))
	while len(A) > 0:
		(s, A) = partial_search(A)
		result = result + s
	print(result)


for _ in range(int(input())):
	input()
	v = [int(e) for e in input().split()]
	sv = sorted(enumerate(v), key=lambda x: x[1])[::-1]
	sv = [e[0] for e in sv]
	lsv = 0
	s = 0
	for i in sv:
		if i < lsv:
			continue
		for j in range(lsv, i):
			s += v[i] - v[j]
		lsv = i + 1
	print(s)


def compute(prices):
	if len(prices) == 0:
		return 0
	m = max(prices)
	pos = prices.index(m)
	return m * pos - sum(prices[:pos]) + compute(prices[pos + 1:])
t = int(input())
for i in range(t):
	n = int(input())
	prices = [int(j) for j in input().split()]
	print(compute(prices))


def solve(prices):
	max_price_from = {}
	for i in reversed(range(len(prices))):
		max_price_from[i] = max(prices[i], max_price_from.get(i + 1, 0))
	num_shares = 0
	balance = 0
	for (i, price) in enumerate(prices):
		if price == max_price_from[i]:
			balance += price * num_shares
			num_shares = 0
		elif price < max_price_from[i]:
			balance -= price
			num_shares += 1
	return balance
T = int(input())
cases = []
for _ in range(T):
	input()
	cases.append([int(x) for x in input().split(' ')])
for x in cases:
	print(solve(x))


t = int(input())
for _ in range(t):
	days = int(input())
	prices = str(input()).split()
	prices = list(map(int, prices))
	dobuy = [1] * len(prices)
	profit = 0
	m = 0
	for i in range(len(prices) - 1, -1, -1):
		ai = prices[i]
		if m <= ai:
			dobuy[i] = 0
			m = ai
		profit += m - ai
	print(profit)


T = int(input())
for i in range(T):
	N = int(input())
	prices = list(map(int, input().split()))
	maxPriceLeft = [0] * N
	maxPriceLeft[N - 1] = prices[N - 1]
	for j in reversed(range(N - 1)):
		maxPriceLeft[j] = max(maxPriceLeft[j + 1], prices[j])
	profit = 0
	for j in range(N):
		if prices[j] < maxPriceLeft[j]:
			profit = profit + maxPriceLeft[j] - prices[j]
	print(profit)


T = int(input())
for i in range(T):
	N = int(input())
	prices = list(map(int, input().split()))
	change = prices[:]
	for i in reversed(range(N - 1)):
		change[i] = max(prices[i], change[i + 1])
	print(sum((max(0, change[i] - prices[i]) for i in range(N))))


import sys
cases = int(sys.stdin.readline().strip())
for x in range(cases):
	sys.stdin.readline()
	prices = [int(x) for x in sys.stdin.readline().strip().split(' ')]
	profit = 0
	cur_peak = 0
	for x in reversed(prices):
		if x > cur_peak:
			cur_peak = x
		elif x < cur_peak:
			profit += cur_peak - x
	print(profit)


T = int(input())
for i in range(T):
	N = int(input())
	priceList = [int(x) for x in input().split()]
	stack = [priceList.pop()]
	profit = 0
	for i in range(N - 1):
		if stack[-1] > priceList[-1]:
			profit += stack[-1] - priceList[-1]
			priceList.pop()
		else:
			stack.append(priceList.pop())
	print(profit)


def solve(case):
	best_upcoming_price_by_index = list(case)
	for (i, x) in reversed(list(enumerate(case[:-1]))):
		best_upcoming_price_by_index[i] = max(best_upcoming_price_by_index[i + 1], x)
	profit = 0
	for (i, x) in enumerate(case):
		profit += max(0, best_upcoming_price_by_index[i] - x)
	return profit
cases = int(input())
for _ in range(cases):
	n = input()
	case = [int(x) for x in input().split()]
	print(solve(case))


def solve(arr, lower, upper):
	max_index = findMax(arr, lower, upper)
	cost = 0
	profit = 0
	if lower >= upper:
		return profit
	for k in range(lower, max_index):
		cost += arr[k]
	profit = (max_index - lower) * arr[max_index] - cost
	if max_index + 1 == upper:
		return profit
	profit += solve(arr, max_index + 1, upper)
	return profit

def findMax(arr, lower, upper):
	max = arr[lower]
	max_index = lower
	for j in range(lower, upper):
		if arr[j] > max:
			max = arr[j]
			max_index = j
	return max_index
T = int(input())
for i in range(T):
	N = int(input())
	prices = [int(i) for i in input().strip().split()]
	profit = solve(prices, 0, len(prices))
	print(profit)


import sys
input = sys.stdin.readlines()[1:]
histories = []
while len(input) > 0:
	histories.append(list(map(int, input[1].split(' '))))
	input = input[2:]

def max_prices(history):
	max_prices = []
	for price in reversed(history):
		last_price = max_prices[-1] if max_prices else -1
		max_price = max((price, last_price))
		max_prices.append(max_price)
	return list(reversed(max_prices))
for history in histories:
	money_made = 0
	for (price, max_price) in zip(history, max_prices(history)):
		if max_price > price:
			money_made += max_price - price
	print(money_made)


def max_profit(prices):
	(max_prices, maxel) = ([], prices[-1])
	for price in reversed(prices):
		if price > maxel:
			maxel = price
		max_prices.insert(0, maxel)
	profit = own_shares = 0
	for (i, _) in enumerate(prices):
		if prices[i] < max_prices[i]:
			profit -= prices[i]
			own_shares += 1
		else:
			profit += prices[i] * own_shares
			own_shares = 0
	return profit
numcases = int(input())
for _ in range(numcases):
	_ = input()
	nums = [int(n) for n in input().strip().split()]
	print(max_profit(nums))


def maximize_profits(arr, n):
	spent = 0
	revenue = 0
	num_to_sell = 0
	p = arr[-1]
	for i in range(1, n):
		cost = arr[n - i - 1]
		if cost >= p:
			revenue += p * num_to_sell
			num_to_sell = 0
			p = cost
		else:
			spent += cost
			num_to_sell += 1
	revenue += p * num_to_sell
	return revenue - spent
tests = int(input())
for i in range(0, tests):
	n = int(input())
	arr = [int(i) for i in input().split()]
	print(maximize_profits(arr, n))


cases = int(input())

def profit(prices):
	if len(prices) == 0:
		return 0
	highest = max(prices)
	ind = prices.index(highest)
	val = -1 * sum(prices[0:ind]) + ind * highest
	return val + profit(prices[ind + 1:])
for case in range(0, cases):
	prices = []
	input()
	line = input()
	for s in line.split(' '):
		prices += [int(s)]
	print(profit(prices))


import sys
T = int(sys.stdin.readline())
for i in range(T):
	N = int(sys.stdin.readline())
	prices = list(map(int, sys.stdin.readline().split()))
	change = prices[:]
	for i in reversed(range(N - 1)):
		change[i] = max(prices[i], change[i + 1])
	print(sum((max(0, change[i] - prices[i]) for i in range(N))))


def solve_case():
	num_days = int(input())
	quotes = list(map(int, input().split(' ')))
	max_cache = [quotes[-1]]
	for i in range(1, num_days):
		max_cache.append(max(quotes[num_days - 1 - i], max_cache[-1]))
	balance = [0, 0]
	for j in range(num_days):
		if quotes[j] < max_cache[num_days - 1 - j]:
			balance[0] += 1
			balance[1] -= quotes[j]
		else:
			balance[1] += quotes[j] * balance[0]
			balance[0] = 0
	print(balance[1])
num_cases = int(input())
for case in range(num_cases):
	solve_case()


numTest = int(input())
for _ in range(numTest):
	numNums = int(input())
	prices = [int(a) for a in input().split()]
	max_current_future_price = 0
	profit = 0
	prices.reverse()
	for i in prices:
		max_current_future_price = max(max_current_future_price, i)
		profit += max_current_future_price - i
	print(profit)


T = int(input())
for t in range(T):
	N = int(input())
	wot = [int(c) for c in input().split(' ')]
	res = 0
	current_max = -1
	for i in reversed(wot):
		current_max = max(current_max, i)
		res += current_max - i
	print(res)


for case in range(int(input())):
	N = int(input())
	prices = [int(x) for x in input().split()]
	shares = 0
	profit = 0
	m = max(prices)
	while len(prices) > 0:
		day = prices.pop(0)
		if day == m:
			profit += day * shares
			shares = 0
			if len(prices) > 0:
				m = max(prices)
		elif day < m:
			profit -= day
			shares += 1
	print(profit)


import sys

def profit(prices, num_days):
	tracker = [0] * num_days
	dp = [0] * num_days
	dp[num_days - 1] = prices[num_days - 1]
	tracker[num_days - 1] = 0
	for i in range(2, num_days + 1):
		i = num_days - i
		if prices[i] >= dp[i + 1]:
			dp[i] = prices[i]
			tracker[i] = tracker[i + 1]
		else:
			dp[i] = dp[i + 1]
			tracker[i] = tracker[i + 1] + dp[i] - prices[i]
	return tracker[0]
num_trials = int(sys.stdin.readline())
for trial in range(num_trials):
	days = int(sys.stdin.readline())
	prices = list((int(p) for p in sys.stdin.readline().split(' ')))
	print(profit(prices, days))


for _ in range(int(input())):
	n = int(input())
	nums = [int(i) for i in input().split()]
	p = 0
	while 1:
		mindex = 0
		maxsum = 0
		tsum = 0
		for i in range(len(nums)):
			if nums[i] > nums[mindex]:
				mindex = i
				maxsum = tsum
			tsum += nums[i]
		p += mindex * nums[mindex] - maxsum
		if mindex == len(nums) - 1:
			break
		else:
			nums = nums[mindex + 1:]
	print(p)


def profit(prices):
	total_prof = 0
	max_price = 0
	for i in range(len(prices), 0, -1):
		price = prices[i - 1]
		temp_prof = max_price - price
		if temp_prof < 0:
			max_price = price
		else:
			total_prof += temp_prof
	return total_prof
num_cases = int(input())
for i in range(num_cases):
	thing = input()
	print(str(profit([int(p) for p in input().split()])))


def getProfit(array):
	if len(array) <= 1:
		return 0
	max = array[len(array) - 1]
	profit = 0
	index = len(array) - 2
	while index >= 0:
		if array[index] > max:
			max = array[index]
		else:
			profit += max - array[index]
		index -= 1
	return profit
numCases = int(input())
for i in range(numCases):
	N = len(input())
	array = [int(x) for x in input().split()]
	print(getProfit(array))


for i in range(int(input())):
	days = int(input())
	values = input().split()
	localMaximum = 0
	profit = 0
	for j in reversed(range(days)):
		value = int(values[j])
		if value >= localMaximum:
			localMaximum = value
		else:
			profit += localMaximum - value
	print(profit)


for t in [1] * int(input()):
	n = int(input())
	a = list(map(int, input().split()))
	m = []
	for ai in reversed(a):
		if len(m):
			m.append(max(m[-1], ai))
		else:
			m.append(ai)
	m.reverse()
	balance = 0
	share = 0
	for i in range(n):
		if i + 1 < n and a[i] < m[i + 1]:
			balance -= a[i]
			share += 1
		else:
			balance += a[i] * share
			share = 0
	print(balance)


def max_stock(prices, size, pos):
	if size - pos <= 1:
		return 0
	max_price = -1
	index = pos
	for i in range(pos, size):
		if prices[i] >= max_price:
			index = i
			max_price = prices[i]
	profit = 0
	num_bought = 0
	for i in range(pos, index):
		profit -= prices[i]
		num_bought += 1
	profit += num_bought * max_price
	return profit + max_stock(prices, size, index + 1)
num_cases = int(input())
for i in range(0, num_cases):
	num = int(input())
	array = input().split()
	array = [int(x) for x in array]
	print(max_stock(array, num, 0))


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


def stock_maximize(shares):
	profit = 0
	bag = 0
	N = len(shares)
	m = max(shares)
	i = 0
	while i < N:
		if shares[i] != m:
			bag += 1
			profit -= shares[i]
			i += 1
			continue
		profit += bag * shares[i]
		if i == N - 1:
			return profit
		shares = shares[i + 1:]
		N = len(shares)
		i = 0
		m = max(shares)
		bag = 0
	return profit
test_cases = int(input())
for t in range(test_cases):
	N = int(input())
	shares = []
	line = input().split(' ')
	for i in range(N):
		shares.append(int(line[i]))
	print(stock_maximize(shares))


import sys
n = int(sys.stdin.readline())
for case in range(n):
	sys.stdin.readline()
	vals = reversed([int(i) for i in sys.stdin.readline().split()])
	s = 0
	maxval = 0
	for val in vals:
		if val < maxval:
			s += maxval - val
		else:
			maxval = val
	print(s)


for i in range(int(input())):
	input()
	days = [int(j) for j in input().split(' ')]
	s = 0
	stocks = 0
	m = len(days)
	mi = 0
	lst = []
	while m != 0:
		m -= 1
		if days[m] > mi:
			mi = days[m]
			lst.append(m)
	for i in range(len(days)):
		if i in lst:
			s += stocks * days[i]
			stocks = 0
		else:
			stocks += 1
			s -= days[i]
	print(s)


def trade(prices, profit=0):
	if len(prices) < 2:
		return profit
	argmax = max(enumerate(prices), key=lambda x: x[1])[0]
	left = prices[:argmax]
	profit += prices[argmax] * len(left) - sum(left)
	profit = trade(prices[argmax + 1:], profit)
	return profit
T = int(input())
for t in range(T):
	n = int(input())
	prices = [int(x) for x in input().strip().split()]
	profit = trade(prices)
	print(profit)


cases = int(input())
for _ in range(cases):
	gains = 0
	count = int(input())
	stocks = [int(i) for i in input().split()]
	while stocks:
		max_v = max(stocks)
		max_index = stocks.index(max_v)
		for i in range(max_index):
			gains += max_v - stocks[i]
		stocks = stocks[max_index + 1:]
	print(gains)


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


t = int(input())
for _ in range(t):
	num_days = int(input())
	price_by_day = [int(i) for i in input().split()]
	sell_days = [False] * num_days
	ind = num_days - 1
	local_max = -1
	while ind >= 0:
		if price_by_day[ind] > local_max:
			sell_days[ind] = True
			local_max = price_by_day[ind]
		ind -= 1
	num_shares = 0
	balance = 0
	for i in range(num_days):
		if not sell_days[i]:
			num_shares += 1
			balance -= price_by_day[i]
		elif num_shares > 0:
			balance += num_shares * price_by_day[i]
			num_shares = 0
	print(balance)


def getMaxProfit(stockPrices, n):
	optimalPrices = [0] * n
	optimalPrices[n - 1] = stockPrices[n - 1]
	for i in range(n - 2, -1, -1):
		optimalPrices[i] = max(stockPrices[i], optimalPrices[i + 1])
	maxProfit = 0
	shares = 0
	for i in range(0, n):
		if i == n - 1 or optimalPrices[i + 1] < optimalPrices[i]:
			maxProfit += shares * optimalPrices[i]
			shares = 0
		elif stockPrices[i] < optimalPrices[i]:
			shares += 1
			maxProfit -= stockPrices[i]
	return maxProfit
testcases = int(input())
for x in range(0, testcases):
	n = int(input())
	prices = [int(p) for p in input().split()]
	print(getMaxProfit(prices, n))


case_count = int(input())
cases = [None for _ in range(case_count)]
for i in range(case_count):
	_ = input()
	cases[i] = [int(j) for j in input().split()]

def find_min_index(min, max, case):
	maximum_value = case[min]
	maximum_idx = min
	for i in range(min + 1, max):
		if case[i] > maximum_value:
			maximum_value = case[i]
			maximum_idx = i
	return maximum_idx
for case in cases:
	last_i = 0
	i = 0
	maximum_sum = 0
	while i < len(case):
		last_i = i
		i = find_min_index(i, len(case), case)
		cost = sum(case[last_i:i])
		total_gain = case[i] * (i - last_i) - cost
		maximum_sum += total_gain
		i += 1
	print(maximum_sum)


from string import *
n = input()
for i in range(0, int(n)):
	n_case = input()
	array = input().split()
	profit = 0
	sell = 0
	for x in range(int(n_case) - 1, -1, -1):
		if int(array[x]) <= sell:
			profit += sell - int(array[x])
		else:
			sell = int(array[x])
	print(profit)


def ma(a, initial, final):
	m = a[initial]
	i = initial
	for k in range(initial + 1, final):
		if a[k] >= m:
			m = a[k]
			i = k
	return [m, i]

def prof_cal(a, n):
	i = 0
	f = n
	prof = 0
	while i < f:
		ar = ma(a, i, f)
		prof = prof + (ar[1] - i) * ar[0] - sum(a[i:ar[1]])
		i = ar[1] + 1
	return prof
t = int(input())
a = []
b = []
for i in range(t):
	b.append(int(input()))
	a.append([])
	for k in input().split():
		a[i].append(int(k))
for i in range(t):
	print(prof_cal(a[i], b[i]))


T = 0
N = 0
nar = []
par = []

def findRightPeak(start):
	maxIndex = start
	maxFromStart = nar[start]
	for pidx in range(start + 1, N):
		if nar[pidx] > maxFromStart:
			maxFromStart = nar[pidx]
			maxIndex = pidx
	par[maxIndex] = 1
	if maxIndex < N - 1:
		findRightPeak(maxIndex + 1)
T = int(input())
for i in range(T):
	N = int(input())
	nar = list(map(int, input().split(' ')))
	par = [0 for i in range(N)]
	share = 0
	cost = 0
	earn = 0
	findRightPeak(0)
	for j in range(N):
		if par[j] == 1:
			earn += nar[j] * share
			share = 0
		else:
			cost += nar[j]
			share += 1
	earn += nar[j] * share
	print(earn - cost)


__author__ = 'abhijsri'
import re
import sys

def getMaxPrice(start, prices):
	profit = 0
	maxIndex = 0
	maxPrice = 0
	for index in range(len(prices)):
		if prices[index] > maxPrice:
			maxPrice = prices[index]
			maxIndex = index
	for index in range(0, maxIndex):
		profit += maxPrice - prices[index]
	if maxIndex < len(prices):
		profit += getMaxPrice(maxIndex, prices[maxIndex + 1:])
	return profit
with sys.stdin as f:
	line = f.readline()
	testCount = int(line)
	for testCase in range(1, testCount + 1):
		line = f.readline()
		size = int(line)
		line = f.readline()
		prices = [int(s) for s in line.split(' ')]
		print(getMaxPrice(0, prices))