import Data.List
import Control.Monad

main :: IO ()
main = print =<< solve . parse . lines <$> getContents

parse :: [String] -> (Int, [Int])
parse (l:ls) = (n, xs)
  where
    n = read . head . words $ l
    xs = map read ls

solve :: (Int,[Int]) -> Int
solve (n, xs) = solve' n xs 0

solve' :: Int -> [Int] -> Int -> Int
solve' n [] d = d
solve' n xs d = solve' n xs' (d + d')
  where
    (d', xs') = if x1 >= (n - x2)
      then (x1, map (subtract x1) (tail xs))
      else (x2, map ((+n) . subtract x2) (init xs))
    x1 = head xs
    x2 = last xs