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

}
ans += cur;
printf("%lld\n",ans);
return 0;
}