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

signed main() {
  int n;
  cin>>n;
  int out=0;
  int ans=0;
  std::vector<int> v(n);
  for(int i=0;i<n;i++)cin>>v[i];
  for(int i=1;i<n;i++)if(v[i]!=v[i-1]+1)ans+=v[i-1];
  if(v[0]!=0)out++;
  for(int i=1;i<n;i++)if(v[i]>v[i-1]+1)out++;
  ans+=v[n-1];
  if(out)cout<<-1<<endl;
  else cout<<ans<<endl;
}
