main = do
    (n:as) <- map read . words <$> getContents :: IO [Int]
    print $ if check as then solve as else (-1)

check as = head as == 0 && and (zipWith f as (tail as))
    where f a b | a + 1 >= b = True
                  | otherwise = False

solve as = fst $ foldl f (0,0) as
    where f (s,a) b | a + 1 == b = (s+1,b)
                    | otherwise = (s+b,b)