N=int(eval(input()))

A=[int(eval(input())) for _ in range(N)]



ans=0

if A[0]!=0:

    print((-1))

    exit()

for i in range(N-1,0,-1):

    l,a=A[i-1],A[i]

    if a>l+1:

        print((-1))

        exit()

    elif a==l+1:

        ans+=1

    elif a!=0:

        ans+=a

print(ans)
import sys

def main():

    input = sys.stdin.readline

    N=int(eval(input()))

    A=[int(eval(input())) for _ in range(N)]



    if A[0]!=0:

        print((-1))

        exit()

    ans=0

    d=0

    for i in range(1,N):

        if A[i]==0: continue

        if A[i]>d+1:

            print((-1))

            exit()

        d=A[i]

        if A[i]==A[i-1]+1:

            ans+=1

        else:

            ans+=A[i]



    print(ans)



if __name__ == '__main__':

    main()
N = int(eval(input()))
A = [int(eval(input())) for _ in range(N)]
ans = 0
if A[0] != 0:
    print((-1))
    exit()
for i in range(N - 1, 0, -1):
    l, a = A[i - 1], A[i]
    if a > l + 1:
        print((-1))
        exit()
    elif a == l + 1:
        ans += 1
    elif a != 0:
        ans += a
print(ans)

import sys


def main():
    input = sys.stdin.readline
    N = int(eval(input()))
    A = [int(eval(input())) for _ in range(N)]
    if A[0] != 0:
        print((-1))
        exit()
    ans = 0
    d = 0
    for i in range(1, N):
        if A[i] == 0:
            continue
        if A[i] > d + 1:
            print((-1))
            exit()
        d = A[i]
        if A[i] == A[i - 1] + 1:
            ans += 1
        else:
            ans += A[i]
    print(ans)


if __name__ == "__main__":
    main()

-N = int(eval(input())) -A = [int(eval(input())) for _ in range(N)] -ans = 0 -if A[0] != 0: -    print((-1)) -    exit() -for i in range(N - 1, 0, -1): -    l, a = A[i - 1], A[i] -    if a > l + 1: +import sys + + +def main(): +    input = sys.stdin.readline +    N = int(eval(input())) +    A = [int(eval(input())) for _ in range(N)] +    if A[0] != 0: -    elif a == l + 1: -        ans += 1 -    elif a != 0: -        ans += a -print(ans) +    ans = 0 +    d = 0 +    for i in range(1, N): +        if A[i] == 0: +            continue +        if A[i] > d + 1: +            print((-1)) +            exit() +        d = A[i] +        if A[i] == A[i - 1] + 1: +            ans += 1 +        else: +            ans += A[i] +    print(ans) + + +if __name__ == "__main__": +    main()