#include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<n;i++)
#define all(x) (x).begin(),(x).end()
#define cyes cout<<"YES"<<endl
#define cno cout<<"NO"<<endl
#define sp <<" "<<
#define cst(x) cout<<fixed<<setprecision(x)
#define pi 3.14159265359
#define mod 1000000007
struct edge {
    int to; 
    int weight;
    edge(int t, int w) : to(t),weight(w) {}
};
using namespace std;
using ll = long long;
using ld = long double;
using Graph = vector<vector<int>>;
using que_a = priority_queue<int, vector<int>, greater<int> >;
using que_d = priority_queue<int>;
using pint = pair<int,int>;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }


int main(){

    int n; cin >> n;
    ll ans = -1;
    int pre = -1;
    bool ok = true;
    rep(i,n){
        int a; cin >> a;
        if(a > pre+1) ok = false;
        else if(a == pre+1) ans++;
        else ans += a;
        pre = a;
    }
    ok? cout << ans << endl : cout << -1 << endl;
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll a[214514];
int main() {
	ll n;
	cin>>n;
	for(int i=0;i<n;i++)cin>>a[i];
	ll ans=0;
	if(a[0]!=0)cout<<-1<<endl;
	else{
		ll cnt=1;
		for(int i=1;i<=n;i++){
			if(a[i]==a[i-1])cnt++;
			else if(a[i]>a[i-1]){
				if(a[i]-a[i-1]>1){
					cout<<-1<<endl;
					return 0;
				}
				ans+=(cnt-1)*a[i-1];
				cnt=1;
			}else{
				ans+=cnt*a[i-1];
				cnt=1;
			}
		}
		cout<<ans<<endl;
	}
	return 0;
}
