program main
    use,intrinsic :: iso_fortran_env
    implicit none
    integer(int64):: i,n,cnt,na
    integer(int64), allocatable:: a(:)

    read*, n
    allocate(a(n))
    do i=1,n
        read*, a(i)
    end do

    cnt=0
    na = a(n)
    if (a(1) /= 0) then
        print'(i0)', -1
        stop
    end if
    do i=n,2,-1
        ! print*, i, a(i-1) == a(i)-1
        if (a(i-1) == a(i)-1) then
            cnt=cnt+1
            na=na-1
            cycle
        end if
        if (a(i) < na) then
            print'(i0)', -1
            stop
        end if
        cnt=cnt+a(i)
        na = a(i)
    end do
    print'(i0)', cnt
end program main