#include <bits/stdc++.h>

using namespace std;

#define int long long

const int N = 2e5 + 100;

int a[N];
int n, cnt;

int32_t main() {
	ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> a[i];
	if (a[0] != 0)
		return cout << -1, 0;
	for (int i = 1; i < n; i++)
		if (a[i] > a[i - 1] + 1)
			return cout << -1, 0;
	for (int i = n - 1; i >= 0; i--)
		if (a[i] > a[i + 1] - 1)
			cnt += a[i];
	return cout << cnt, 0;	
}
