import Control.Monad (replicateM)
import Data.ByteString.Char8 as C (readInteger, getLine)
import Data.Maybe

getNIntegers :: Int -> IO [Integer]
getNIntegers n = map (fst . fromJust . readInteger) <$> replicateM n C.getLine

f :: [Integer] -> Maybe Integer
f [_] = Just 0
f (a:b:bs) =
  case compare (a + 1) b of
    LT -> Nothing
    EQ -> fmap (+ 1) (f (b:bs))
    GT -> fmap (+ b) (f (b:bs))

f' :: [Integer] -> Maybe Integer
f' a =
  if head a == 0
    then f a
    else Nothing

main = do
  n <- readLn :: IO Int
  a <- getNIntegers n :: IO [Integer]
  print $ case f' a of
            Just i  -> i
            Nothing -> -1