#include <bits/stdc++.h>
using namespace std;
 
long long n, a[200010], ans = 0;
int main() {
	scanf("%lld", &n);
	for(int i = 0; i < n; i++) scanf("%lld", &a[i]);
	if(a[0]) return !printf("-1");
	a[n] = a[n-1];
	for(int i = 1; i <= n; i++) {
		if(a[i] - a[i-1] > 1) return !printf("-1");
		if(a[i] <= a[i-1]) ans += a[i-1];
	}
	printf("%lld", ans);
}