#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n;
vector<int> d;
vector<int> bit;
void upd(int i, int v) {
for (; i < n; i += (i+1) & (-i-1)) {
bit[i] += v;
}
}
int query(int i) {
int res = 0;
for (; i >= 0; i -= (i+1) & (-i-1)) {
res += bit[i];
}
return res;
}
int main() {
ios::sync_with_stdio(0), cin.tie(0);
cin >> n;
d.resize(n);
for (int i = 0; i < n; i++) {
cin >> d[i];
d[i]--;
}
vector<int> p(n);
set<int> zz;
for (int i = 0; i < n; i++) zz.insert(i);
for (int i = n-1; i >= 0; i--) {
set<int>::iterator it = zz.upper_bound(d[i]);
if (it == zz.begin()) {
cout << -1 << '\n';
exit(0);
}
--it;
p[i] = *it;
zz.erase(it);
}
bit.resize(n);
ll tot = 0;
for (int i = 0; i < n; i++) {
tot += i - query(p[i]);
upd(p[i], 1);
}
cout << tot << '\n';
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7Cgp0eXBlZGVmIGxvbmcgbG9uZyBsbDsKCmludCBuOwp2ZWN0b3I8aW50PiBkOwoKdmVjdG9yPGludD4gYml0OwoKdm9pZCB1cGQoaW50IGksIGludCB2KSB7Cglmb3IgKDsgaSA8IG47IGkgKz0gKGkrMSkgJiAoLWktMSkpIHsKCQliaXRbaV0gKz0gdjsKCX0KfQoKaW50IHF1ZXJ5KGludCBpKSB7CglpbnQgcmVzID0gMDsKCWZvciAoOyBpID49IDA7IGkgLT0gKGkrMSkgJiAoLWktMSkpIHsKCQlyZXMgKz0gYml0W2ldOwoJfQoJcmV0dXJuIHJlczsKfQoKaW50IG1haW4oKSB7Cglpb3M6OnN5bmNfd2l0aF9zdGRpbygwKSwgY2luLnRpZSgwKTsKCWNpbiA+PiBuOwoJZC5yZXNpemUobik7Cglmb3IgKGludCBpID0gMDsgaSA8IG47IGkrKykgewoJCWNpbiA+PiBkW2ldOwoJCWRbaV0tLTsKCX0KCXZlY3RvcjxpbnQ+IH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