#include <bits/stdc++.h>
using namespace std;

#define all(x) (x).begin(), (x).end()
using lli = long long int;
template <typename T>
vector<T> read_vector(int n) {
  vector<T> result(n);
  for (auto& a : result) cin >> a;
  return result;
}
template <typename T>
vector<T> read_vector() {
  int n;
  cin >> n;
  return read_vector<T>(n);
}

int main() {
  ios_base::sync_with_stdio(false);
  auto v = read_vector<int>();
  bool valid = v[0] == 0;
  for (int i = 1; i < v.size(); ++i) valid &= v[i] <= v[i - 1] + 1;
  if (!valid) {
    cout << -1;
    return 0;
  }
  lli cost = 0;
  int prev = 0;
  reverse(all(v));
  for (auto a : v) {
    prev = max(0, prev - 1);
    if (a < prev) {
      cout << -1;
      return 0;
    } else if (a > prev) {
      cost += a;
    }
    prev = a;
  }
  cout << cost;
  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;
}
