loop do
    n = gets.to_i
    break if n == 0
    a = gets.split.map(&:to_i)
    k = a.inject(:+)
    n = 1
    n += 1 until n * (n + 1) / 2 >= k
    if k != n * (n + 1) / 2
        puts -1
        next
    end
    goal = (1..n).to_a
    k = 0
    loop do
        break if a == goal
        b = []
        s = a.size
        until a.empty?
            x = a.shift
            b << x - 1 if x > 1
        end
        b << s
        a = b
        k += 1
        if k == 10000
            k = -1
            break
        end
    end
    puts k
end
