import Control.Applicative

apply_maybe :: (a -> b) -> Maybe a -> Maybe b
apply_maybe _ Nothing = Nothing
apply_maybe f (Just a) = Just $ f a

sge' :: [Int] -> Maybe Int
sge' [_] = Just 0
sge' (a:(r@(b:_))) | b <= a     = apply_maybe (b +) $ sge' r
sge' (a:(r@(b:_))) | b == a + 1 = apply_maybe (1 +) $ sge' r
sge' _                          = Nothing

sge :: [Int] -> Int
sge l@(0:_) = case sge' l of
    Nothing -> -1
    Just r  -> r
sge _ = -1

main :: IO ()
main = do
    n <- readLn
    a <- mapM (\_->readLn) [1..n]
    putStrLn $ show $ sge a
