Arkady decides to observe a river for n consecutive days. The river's water level on each day is equal to some real value.

Arkady goes to the riverside each day and makes a mark on the side of the channel at the height of the water level, but if it coincides with a mark made before, no new mark is created. The water does not wash the marks away. Arkady writes down the number of marks strictly above the water level each day, on the i-th day this value is equal to m_{i}.

Define d_{i} as the number of marks strictly under the water level on the i-th day. You are to find out the minimum possible sum of d_{i} over all days. There are no marks on the channel before the first day.


-----Input-----

The first line contains a single positive integer n (1 ≤ n ≤ 10^5) — the number of days.

The second line contains n space-separated integers m_1, m_2, ..., m_{n} (0 ≤ m_{i} < i) — the number of marks strictly above the water on each day.


-----Output-----

Output one single integer — the minimum possible sum of the number of marks strictly below the water level among all days.


-----Examples-----
Input
6
0 1 0 3 0 2

Output
6

Input
5
0 1 2 1 2

Output
1

Input
5
0 1 1 2 2

Output
0



-----Note-----

In the first example, the following figure shows an optimal case. [Image] 

Note that on day 3, a new mark should be created because if not, there cannot be 3 marks above water on day 4. The total number of marks underwater is 0 + 0 + 2 + 0 + 3 + 1 = 6.

In the second example, the following figure shows an optimal case. [Image]

Difficulty: MEDIUM_HARD
Tags: Dynamic programming

Data structures

Greedy algorithms
Skill types: Dynamic programming

Data structures

Greedy algorithms
Expected Time Complexity: O(N)

Starter code:

Solutions:
n = int(input())
above = list(map(int, input().split()))
total = [x + 1 for x in above]
for i in range(0, n - 1)[::-1]:
	total[i] = max(total[i], total[i + 1] - 1)
for i in range(1, n):
	total[i] = max(total[i], total[i - 1])
below = [t - a - 1 for (t, a) in zip(total, above)]
print(sum(below))


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


def main():
	n = int(input())
	arr = list(map(int, input().split()))
	b = []
	b.append(1)
	for i in range(1, n):
		if arr[i] >= b[i - 1]:
			b.append(arr[i] + 1)
		else:
			b.append(b[i - 1])
	for i in range(n - 2, 0, -1):
		if b[i] < b[i + 1] - 1:
			b[i] = b[i + 1] - 1
	ans = 0
	for i in range(0, n):
		ans += b[i] - arr[i] - 1
	print(ans)
main()


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

def main():
	n = int(input())
	m = tuple(readline())
	md = [None] * n
	prev = 0
	for i in range(n):
		prev = md[i] = max(prev, m[i])
	prev = 0
	for i in range(n - 1, -1, -1):
		prev -= 1
		prev = md[i] = max(prev, md[i])
	print(sum(md) - sum(m))
main()


n = int(input())
m = list(map(int, input().split()))
num = [0 for _ in range(n)]
cur = 0
for i in range(n - 1, -1, -1):
	cur -= 1
	alt = m[i] + 1
	if cur < alt:
		cur = alt
		j = i
		while j < n and num[j] < cur:
			num[j] = cur
			j += 1
	else:
		num[i] = cur
print(sum(num) - n - sum(m))


def read_data():
	n = int(input().strip())
	a = list(map(int, list(input().strip().split())))
	return (n, a)

def solve():
	under = [0 for i in range(n)]
	under[-1] = a[-1] + 1
	for i in range(n - 2, -1, -1):
		under[i] = max(a[i] + 1, a[i + 1], under[i + 1] - 1)
	for i in range(1, n):
		under[i] = max(under[i], under[i - 1])
	return sum((under[i] - 1 - a[i] for i in range(n)))
(n, a) = read_data()
print(solve())


n = int(input())
m = list(map(int, input().split()))
starts = sorted([(i - m[i], i) for i in range(n)], reverse=True)
cur = answer = 0
for i in range(n):
	while starts[-1][1] < i:
		starts.pop()
	cur = max(cur, i - starts[-1][0])
	answer += cur - m[i]
print(answer)


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
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')
n = int(input())
m = list(map(int, input().split()))
t = [1] * n
for i in range(1, n):
	t[i] = max(t[i - 1], m[i] + 1)
for i in range(n - 2, -1, -1):
	t[i] = max(t[i], t[i + 1] - 1)
summ = 0
for i in range(n):
	summ += t[i] - m[i] - 1
print(summ)


n = int(input())
m = input().split(' ')
j = 0
mark = [1]
for i in range(1, len(m)):
	tmp = max(mark[i - 1], int(m[i]) + 1)
	mark.append(tmp)
j += mark[len(m) - 1] - int(m[len(m) - 1]) - 1
for i in range(len(m) - 2, -1, -1):
	if mark[i] < mark[i + 1] - 1:
		mark[i] = mark[i + 1] - 1
	j += mark[i] - int(m[i]) - 1
print(j)


N = int(input())
above = list(map(int, input().split()))
if N == 1:
	print(0)
	quit()
required_mark = [0] * N
required_mark[N - 2] = above[N - 1]
for i in reversed(range(N - 2)):
	required_mark[i] = max(above[i + 1], required_mark[i + 1] - 1)
d = 0
mark = 1
for i in range(1, N):
	if mark == above[i]:
		mark += 1
	elif mark >= required_mark[i]:
		d += mark - above[i] - 1
	else:
		d += mark - above[i]
		mark += 1
print(d)


def f(ar):
	mx = ar.index(max(ar))
	cmark = 0
	ans = 0
	big = [0] * len(ar)
	for i in range(len(ar) - 1, -1, -1):
		cmark = max(cmark - 1, ar[i] + 1, 0)
		big[i] = cmark
	cmark = 0
	t = [0] * len(ar)
	for i in range(len(ar)):
		cmark = max(cmark, big[i])
		t[i] = cmark
	ans = 0
	for i in range(len(ar)):
		t[i] = t[i] - ar[i] - 1
	return sum(t)
a = input()
print(f([*map(int, input().strip().split())]))


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


from sys import stdin, stdout

def rint():
	return map(int, stdin.readline().split())
n = int(input())
u = list(rint())
u = [0] + u
mark = 0
b = [0]
for i in range(1, n + 1):
	uu = u[i]
	b.append(i)
	if uu >= mark:
		inc = uu - mark + 1
		l = len(b)
		for i in range(inc):
			b.pop()
		mark += inc
tot = [1 for i in range(n + 1)]
for bb in b:
	tot[bb] = 0
for i in range(1, n + 1):
	tot[i] = tot[i - 1] + tot[i]
ans = 0
for i in range(1, n + 1):
	ans += tot[i] - u[i] - 1
print(ans)


import sys
from collections import deque
data = sys.stdin.read().split()
data_ptr = 0

def data_next():
	nonlocal data_ptr, data
	data_ptr += 1
	return data[data_ptr - 1]
N = int(data_next())
tot_lines = 0
ans = 0
st = deque()
for i in range(N):
	n = int(data_next())
	if n >= tot_lines:
		for j in range(n - tot_lines):
			prev_repeat = st.pop()
			ans += i - prev_repeat
		tot_lines = n + 1
	else:
		ans += tot_lines - n - 1
		st.append(i)
print(ans)


n = int(input())
a = list(map(int, input().split()))
ma = [1] * n
for i in range(1, n):
	ma[i] = max(ma[i - 1], a[i] + 1)
for i in range(n - 2, -1, -1):
	ma[i] = max(ma[i + 1] - 1, ma[i])
print(sum(ma) - sum(a) - n)


import sys
import math
n = int(input())
arr = [int(i) for i in input().split()]
tt = [0] * n
for i in range(n):
	if i != 0:
		tt[i] = max(tt[i - 1], arr[i] + 1)
	else:
		tt[i] = arr[i] + 1
ss = 0
for i in range(n - 1, -1, -1):
	if i != n - 1:
		tt[i] = max(tt[i + 1] - 1, tt[i])
		ss += tt[i] - arr[i] - 1
	else:
		ss += tt[i] - arr[i] - 1
print(ss)


n = int(input())
Ab = input().split()
Un = []
Al = [0]
r = 0
for i in range(n):
	Ab[i] = int(Ab[i])
	Al.append(max(Ab[i] + 1, Al[i]))
for i in range(n, -1, -1):
	if Al[i - 1] < Al[i] - 1:
		Al[i - 1] = Al[i] - 1
for i in range(n):
	Un.append(Al[i + 1] - Ab[i] - 1)
	r += Un[-1]
print(r)


n = int(input())
a = input().split(' ')
for i in range(len(a)):
	a[i] = int(a[i])
khat = n * [0]
ted = 0
assl = 0
khat[0] = 1
lol = [0, 0]
for i in range(1, len(khat)):
	khat[i] = max([khat[i - 1], a[i] + 1])
for i in range(len(khat) - 2, -1, -1):
	if khat[i] < khat[i + 1] - 1:
		khat[i] = khat[i + 1] - 1
	ted = ted + (khat[i] - (a[i] + 1))
ted = ted + (khat[n - 1] - (a[n - 1] + 1))
print(ted)


import math
import sys
from collections import deque
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 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
	mid = 0
	while left < right:
		mid = (right + left) // 2
		if arr[mid] == key:
			while mid + 1 < n and arr[mid + 1] == key:
				mid += 1
			break
		elif arr[mid] > key:
			right = mid
		else:
			left = mid + 1
	while mid > -1 and arr[mid] > key:
		mid -= 1
	return mid + 1

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
n = int(input())
l = list(map(int, input().split()))
prev = -1
ans = [i for i in range(n)]
diff = [0] * n
for i in range(n):
	diff[i] = ans[i] - l[i]
ind = [i for i in range(n)]
const = [0] * n
ans = sort_list(ans, diff)
diff.sort()
t = 0
final = [0] * n
for i in range(n):
	if i > ans[t]:
		while ans[t] < i:
			t += 1
	const[i] = max(prev, l[i])
	if ind[i] - const[i] > diff[t]:
		const[i] = ind[i] - diff[t]
	prev = const[i]
const = [const[i] - l[i] for i in range(n)]
print(sum(const))


n = int(input())
l = [int(x) for x in input().split()]
distinct = []
cur = 0
for i in l:
	cur = max(cur, i + 1)
	distinct.append(cur)
for i in range(n - 1, 0, -1):
	distinct[i - 1] = max(distinct[i - 1], distinct[i] - 1)
ans = sum([a - b - 1 for (a, b) in zip(distinct, l)])
print(ans)


n = int(input())
A = [int(x) for x in input().split()]
n = len(A)
LB = [0] * n
lvl = 0
for i in reversed(range(n)):
	lvl = max(A[i], lvl)
	LB[i] = lvl + 1
	lvl -= 1
poss = [[1, 1]]
for i in range(1, n):
	(l, h) = poss[-1]
	a = A[i]
	l = max(a, l)
	if a == h:
		l += 1
	poss.append([l, h + 1])
Level = []
for i in range(n):
	if Level:
		Level.append(max(Level[-1], LB[i], poss[i][0]))
	else:
		Level.append(max(LB[i], poss[i][0]))
count = 0
for i in range(n):
	count += max(1, Level[i] - A[i]) - 1
print(count)


N = int(input())
M = list(map(int, input().split()))
T = [0] * N
for i in range(1, N):
	T[i] = max(T[i - 1], M[i] + 1)
for i in range(N - 2, -1, -1):
	T[i] = max(T[i], T[i + 1] - 1, 0)
res = sum([max(0, T[i] - M[i] - 1) for i in range(N)])
print(res)


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

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

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

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


n = int(input())
m = input().split()
t = []
for i in range(n):
	m[i] = int(m[i])
	if i == 0:
		t.append(m[i] + 1)
	else:
		t.append(max(t[i - 1], m[i] + 1))
s = t[n - 1] - m[n - 1] - 1
for i in range(n - 2, -1, -1):
	if t[i] < t[i + 1] - 1:
		t[i] = t[i + 1] - 1
	s += t[i] - m[i] - 1
print(s)


n = int(input())
a = list(map(int, input().strip().split()))
s = [0] * n
under = 0
for i in range(n):
	s[i] = a[i]
for i in range(1, n):
	s[i] = max(s[i], s[i - 1])
for i in range(n - 2, 0, -1):
	if s[i + 1] - s[i] > 1:
		s[i] = s[i + 1] - 1
for i in range(n):
	under += max(0, s[i] - a[i])
print(under)


k = int(input())
o = [*map(int, input().split())]
list1 = [0] * k
y = 0
for j in range(k):
	y = max(y, o[j] + 1)
	list1[j] = y
for z in range(k - 1, 0, -1):
	list1[z - 1] = max(list1[z - 1], list1[z] - 1)
list2 = zip(list1, o)
print(sum((x - f - 1 for (x, f) in list2)))


n = int(input())
a = list(map(int, input().split()))
min_toptal = a.copy()
for i in range(1, n):
	min_toptal[i] = max(min_toptal[i - 1], a[i] + 1)
min_toptal[0] = 1
for i in range(n - 1, 0, -1):
	min_toptal[i - 1] = max(min_toptal[i] - 1, min_toptal[i - 1])
min_under = []
underwater = sum((max(0, min_toptal[i] - a[i] - 1) for i in range(n)))
print(underwater)


import sys
n = int(input())
a = [int(x) for x in input().split(' ')]
maxm = 0
idx = 0
ans = 0
b = [0] * n
for i in range(n):
	if a[i] >= maxm:
		maxm = a[i]
		idx = i
for i in range(idx, n):
	b[i] = maxm + 1
i = idx - 1
while i >= 0:
	b[i] = max(a[i] + 1, b[i + 1] - 1)
	i -= 1
for i in range(1, n):
	if b[i] < b[i - 1]:
		b[i] = b[i - 1]
	ans += b[i] - 1 - a[i]
print(ans)


n = int(input())
m = [int(i) for i in input().split()]
dm = [0 for i in range(n)]
dm[-1] = m[-1] + 1
for i in range(n - 2, -1, -1):
	dm[i] = max(m[i] + 1, m[i + 1], dm[i + 1] - 1)
for i in range(1, n):
	dm[i] = max(dm[i], dm[i - 1])
print(sum([dm[i] - 1 - m[i] for i in range(n)]))


import sys
n = int(sys.stdin.readline().strip())
integer_line = sys.stdin.readline().strip().split()
integers = []
for integer in integer_line:
	integers.append(int(integer))
marks = integers[:]
marks[0] = 1
for index in range(1, len(integers)):
	marks[index] = max(marks[index - 1], marks[index] + 1)
for index in range(len(integers) - 1, 0, -1):
	marks[index - 1] = max(marks[index] - 1, marks[index - 1])
for index in range(len(integers)):
	marks[index] -= integers[index] + 1
sys.stdout.write(str(sum(marks)) + '\n')


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


n = int(input())
a = list(map(int, input().split()))
ne = n * [0]
ned = 1
for i in range(n - 1, -1, -1):
	if a[i] + 1 > ned:
		ned = a[i] + 1
	ne[i] = ned
	ned -= 1
ne.append(0)
le = 1
o = 0
for i in range(n):
	o += le - a[i] - 1
	if le < ne[i + 1]:
		le += 1
print(o)


n = int(input())
a = list(map(int, input().split()))
b = []
maxi = 0
for i in range(n):
	maxi = max(maxi, a[i] + 1)
	b.append(maxi)
c = []
count = b[-1]
for i in range(n - 1, -1, -1):
	if count - 1 >= b[i]:
		count -= 1
		c.append(count)
	else:
		c.append(count)
c = c[::-1]
ans = 0
for i in range(n):
	ans += c[i] - a[i] - 1
print(ans)