Skip to content

Commit be178d2

Browse files
committed
Optimise making change memoisation
1 parent 2a008a8 commit be178d2

1 file changed

Lines changed: 25 additions & 28 deletions

File tree

Lines changed: 25 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,44 @@
11
from typing import List
22

3-
cache = {}
3+
COINS = [200, 100, 50, 20, 10, 5, 2, 1]
44

55

66
def ways_to_make_change(total: int) -> int:
77
"""
88
Given access to coins with the values 1, 2, 5, 10, 20, 50, 100, 200,
99
returns a count of all of the ways to make the passed total value.
1010
"""
11-
cache.clear()
12-
return ways_to_make_change_helper(
13-
total,
14-
[200, 100, 50, 20, 10, 5, 2, 1]
15-
)
11+
cache = {}
1612

13+
def helper(total: int, start_index: int) -> int:
14+
key = (total, start_index)
1715

18-
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
19-
key = (total, tuple(coins))
16+
if key in cache:
17+
return cache[key]
2018

21-
if key in cache:
22-
return cache[key]
19+
if total == 0 or start_index >= len(COINS):
20+
return 0
2321

24-
if total == 0 or len(coins) == 0:
25-
return 0
22+
ways = 0
2623

27-
ways = 0
24+
for coin_index in range(start_index, len(COINS)):
25+
coin = COINS[coin_index]
26+
count_of_coin = 1
2827

29-
for coin_index in range(len(coins)):
30-
coin = coins[coin_index]
31-
count_of_coin = 1
28+
while coin * count_of_coin <= total:
29+
total_from_coins = coin * count_of_coin
3230

33-
while coin * count_of_coin <= total:
34-
total_from_coins = coin * count_of_coin
31+
if total_from_coins == total:
32+
ways += 1
33+
else:
34+
ways += helper(
35+
total - total_from_coins,
36+
coin_index + 1
37+
)
3538

36-
if total_from_coins == total:
37-
ways += 1
38-
else:
39-
ways += ways_to_make_change_helper(
40-
total - total_from_coins,
41-
coins[coin_index + 1:]
42-
)
39+
count_of_coin += 1
4340

44-
count_of_coin += 1
41+
cache[key] = ways
42+
return ways
4543

46-
cache[key] = ways
47-
return ways
44+
return helper(total, 0)

0 commit comments

Comments
 (0)