Skip to content

Commit 4d665b2

Browse files
committed
Improve efficiency with cached results
1 parent cf6ba23 commit 4d665b2

1 file changed

Lines changed: 17 additions & 5 deletions

File tree

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,28 @@
11
from typing import List
22

3-
3+
# ===============> change function <============
44
def ways_to_make_change(total: int) -> int:
55
"""
66
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.
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])
11-
10+
# Initialize a cache dictionary
11+
cache = {}
12+
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1], cache)
1213

13-
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
14+
# =================> change helper function <==============
15+
def ways_to_make_change_helper(total: int, coins: List[int], cache: dict) -> int:
1416
"""
1517
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1618
"""
19+
# Create unique key for this subproblem
20+
cache_key = (total, tuple(coins))
21+
22+
# Return cached result if already calculated
23+
if cache_key in cache:
24+
return cache[cache_key]
25+
1726
if total == 0 or len(coins) == 0:
1827
return 0
1928

@@ -26,7 +35,10 @@ def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
2635
if total_from_coins == total:
2736
ways += 1
2837
else:
29-
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:])
38+
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:], cache=cache)
3039
ways += intermediate
3140
count_of_coin += 1
41+
42+
# Save result before returning
43+
cache[cache_key] = ways
3244
return ways

0 commit comments

Comments
 (0)