import qualified Data.IntMap.Strict as M import Data.List main = getContents >>= print . sushi . map read . tail . words sushi = fst . M.findMax . foldl dp (M.singleton 0 True) dp im v = M.insertWith (||) (fst (M.findMax im)) True im' where im' = M.map (const False) $ M.mapKeys (+v) (M.filter id im)