Skip to content

Commit 1be1ae2

Browse files
committed
Refactor ways_to_make_change to use memoization
1 parent c5aed12 commit 1be1ae2

1 file changed

Lines changed: 19 additions & 10 deletions

File tree

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,41 @@
1-
from typing import List
2-
1+
from typing import List, Dict, Tuple
32

43
def ways_to_make_change(total: int) -> int:
54
"""
65
Given access to coins with the values 1, 2, 5, 10, 20, 50, 100, 200, returns a count of all of the ways to make the passed total value.
76
87
For instance, there are two ways to make a value of 3: with 3x 1 coins, or with 1x 1 coin and 1x 2 coin.
98
"""
10-
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1])
9+
coins = [200, 100, 50, 20, 10, 5, 2, 1]
10+
memo: Dict[Tuple[int, int], int] = {}
11+
return ways_to_make_change_helper(total, coins, memo)
1112

1213

13-
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
14+
def ways_to_make_change_helper(total: int, coins: List[int], memo: Dict[Tuple[int, int], int]) -> int:
1415
"""
1516
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
17+
Uses memoization to cache results for (total, coin_index).
1618
"""
17-
if total == 0 or len(coins) == 0:
18-
return 0
19+
if total == 0:
20+
return 1
21+
if total < 0 or not coins:
22+
return 0
23+
24+
key = (total, len(coins))
25+
if key in memo:
26+
return memo[key]
1927

2028
ways = 0
2129
for coin_index in range(len(coins)):
2230
coin = coins[coin_index]
2331
count_of_coin = 1
2432
while coin * count_of_coin <= total:
25-
total_from_coins = coin * count_of_coin
26-
if total_from_coins == total:
33+
remainder = total - coin * count_of_coin
34+
if remainder == 0:
2735
ways += 1
2836
else:
29-
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:])
30-
ways += intermediate
37+
ways += ways_to_make_change_helper(remainder, coins[coin_index + 1:], memo)
3138
count_of_coin += 1
39+
40+
memo[key] = ways
3241
return ways

0 commit comments

Comments
 (0)