Skip to content

Commit edb0807

Browse files
committed
add cache to speed up computation
1 parent a6b9f98 commit edb0807

File tree

1 file changed

+23
-15
lines changed

1 file changed

+23
-15
lines changed
Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import List
1+
from typing import Dict, List, Tuple
22

33

44
def ways_to_make_change(total: int) -> int:
@@ -7,26 +7,34 @@ def ways_to_make_change(total: int) -> int:
77
88
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.
99
"""
10-
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1])
10+
cache: Dict[Tuple[int, int], int] = {} # Initialize cache
11+
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1], cache, 0)
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], cache: Dict[Tuple[int, int], int], coin_index: int) -> int:
1415
"""
1516
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1617
"""
17-
if total == 0 or len(coins) == 0:
18+
if total == 0:
19+
return 1
20+
if total < 0 or coin_index >= len(coins):
1821
return 0
22+
23+
24+
# Check cache
25+
key = (total, coin_index)
26+
if key in cache:
27+
return cache[key]
1928

2029
ways = 0
21-
for coin_index in range(len(coins)):
22-
coin = coins[coin_index]
23-
count_of_coin = 1
24-
while coin * count_of_coin <= total:
25-
total_from_coins = coin * count_of_coin
26-
if total_from_coins == total:
27-
ways += 1
28-
else:
29-
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:])
30-
ways += intermediate
31-
count_of_coin += 1
30+
coin = coins[coin_index]
31+
count_of_coin = 1
32+
while coin * count_of_coin <= total:
33+
remaining = total - coin * count_of_coin
34+
ways += ways_to_make_change_helper(remaining, coins, cache, coin_index + 1)
35+
count_of_coin += 1
36+
37+
ways += ways_to_make_change_helper(total, coins, cache, coin_index + 1)
38+
39+
cache[key] = ways # Store result in cache
3240
return ways

0 commit comments

Comments
 (0)