• + 0 comments

    no bfs, no dp. Just simple math. Also, handles more stricter test cases.

    solve :: ([Int], Int) -> [Int]
    solve (s,n) = foldl (\r partS -> 
                                    let 
                                        f = factors partS n [] 
                                        lenf = length f
                                        lenr = length r
                                        check = mod n (head partS) == 0
                                    in 
                                        if not check then 
                                            r 
                                        else if not (null f) && (lenr > lenf || null r) then f else if lenr == lenf then min r f else r
                        ) [] $ init $ tails rs
        where
            rs = sortBy (flip compare) s
    
            factors _ 1 acc = 1:acc
            factors [] _ _ = []
            factors s@(a:as) n acc
                | mod n a == 0 = factors s (div n a) (n:acc)
                | otherwise = factors as n acc