Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Data.Maybe
- import Data.List
- import qualified Data.Map as Map
- countExchanges :: (Integral a) => a -> [a] -> a
- countExchanges sum coins = fst $ count sum sorted_coins Map.empty
- where count _ [] cache = (0, cache)
- count sum coins cache
- | isJust cached = (fromJust cached, cache)
- | sum == 0 = memorize 1 cache
- | sum < 0 = memorize 0 cache
- | otherwise = let (left, updated_cache) = count (sum - head coins) coins cache
- (right, final_cache) = count sum (tail coins) updated_cache
- in
- memorize (left + right) final_cache
- where cached = Map.lookup key cache
- key = (sum, head coins)
- memorize result target_cache = (result, Map.insert key result target_cache)
- sorted_coins = reverse $ sort coins
- main = print (countExchanges 100000 [50, 25, 10, 5, 1])
Add Comment
Please, Sign In to add comment