def calculate(walls):
	prev = 0
	max = 0
	localSum = 0
	totalSum = 0

	for i in xrange(len(walls)):
		if i < prev and max == 0:
			max = prev

		if walls[i] >= max:
			max = 0
			totalSum += localSum
			localSum = 0

		if not max == 0:
			localSum += max - walls[i]

		prev = walls[i]
	return totalSum

print calculate([2, 5, 1, 2, 3, 4, 7, 7, 6])