main = getLine >>= main' . read . last . words
    where
        main' x = getLine >>= print . solve x . map read . words

solve :: Int -> [Int] -> Int
solve x = rec
    where
        rec (a : b : cs)
            | a + b > x && x >= a = a + b - x + rec (x - a : cs)
            | a + b > x = a - x + b + rec (0 : cs)
            | otherwise = rec (b : cs)
        rec _ = 0
