• + 0 comments

    Haskell

    module Main where
    
    import Data.List (group, nub, tails)
    import Data.Maybe (mapMaybe)
    
    onlyKeep :: (Eq a) => [a] -> [a] -> [a]
    onlyKeep originals keepers = filter (`elem` keepers) originals
    
    allPairs :: [a] -> [[a]]
    allPairs xs = [[x, y] | (x : ys) <- tails xs, y <- ys]
    
    lengthIfValid :: (Eq a) => [a] -> Maybe Int
    lengthIfValid s =
        if and $ zipWith (/=) s (tail s)
            then Just $ length s
            else Nothing
    
    solve :: (Eq a) => [a] -> Int
    solve [] = 0
    solve s =
        let us = nub s
            pairs = allPairs us
            ls = mapMaybe (lengthIfValid . onlyKeep s) pairs
         in maximum $ 0 : ls
    
    main :: IO ()
    main = getLine >> getLine >>= print . solve