import Control.Applicative import Data.List import Data.IntMap (IntMap, (!)) import qualified Data.IntMap as IM main :: IO () main = solve <$> getLine >>= print solve :: String -> Int solve = (\(_, _, x, _) -> x) . foldl' f (1, IM.insert 0 0 IM.empty, 0, 0) where f (i, mp, mx, d) c | IM.member nd mp = (i+1, mp, max mx (i - mp ! nd), nd) | otherwise = (i+1, IM.insert nd i mp, mx, nd) where nd = if c == 'A' then d+1 else d-1