#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e6+1;

int n,a[N];
ll ans;

int main(){
	cin>>n;
	for(int i=1;i<=n;++i)scanf("%d",&a[i]);
	for(int i=1;i<=n;++i)if(a[i]>=i||a[i]>a[i-1]+1)return 0*printf("-1\n");
	int l=n;
	for(int i=n;~i;--i){
		if(a[i]==a[i+1]-1)continue;
		ans+=a[i];
	}
	cout<<ans<<endl;
}