parkerjgit
6/14/2018 - 2:33 AM

Optimized solution to coin change problem

Optimized solution to coin change problem

def coinChange(coins, cost):
        
    memo = {}
    
    def _ch(cid, rst, cnt):
            
        if rst < 0 or cid > len(coins)-1:
            return float('inf')
        
        if rst % coins[cid] == 0:           
            return cnt + (rst // coins[cid])  
        
        if rst % coins[cid] > 0: 
            
            take1 = (cid, rst-coins[cid], cnt+1)
            take0 = (cid+1, rst, cnt) 
             
            memo[take1] = memo[take1] if take1 in memo else _ch(*take1)
            memo[take0] = memo[take0] if take0 in memo else _ch(*take0)  
                        
            return min(memo[take1], memo[take0])
  
    return _ch(0, cost, 0)