import Control.Applicative ((<$>), (<*>))
import Control.Monad
import Data.List

main :: IO ()
main = do
  n <- getl toInt
  unless (n == 0) $ do
    solve <$> getl (wrds toInt) >>= print
    main

solve :: [Int] -> Int
solve xs
  | n == (-1) = (-1)
  | otherwise = count 0 xs
  where
    n = eot (sum xs)
    move ys = filter (/= 0) $ map (subtract 1) ys ++ [length ys]
    g = [1..n]
    count c zs
      | zs == g = c
      | c > 10000 = (-1)
      | otherwise = count (c+1) (move zs)
      
eot :: Int -> Int
eot x = if x == n * (n + 1) `div` 2 then n else (-1)
  where
    n = round $ (sqrt (8.0 * (fromIntegral x) + 1.0) - 1.0) / 2.0

toInt :: String -> Int
toInt = read

wrds :: (String -> a) -> String -> [a]
wrds f = map f . words

getl :: (String -> a) -> IO a
getl f = f <$> getLine