Skip to content

Commit d79042c

Browse files
committed
refactor: optimize making_change to use tuple with index parameter
1 parent 8b092d9 commit d79042c

File tree

1 file changed

+8
-13
lines changed

1 file changed

+8
-13
lines changed
Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,38 @@
1-
from typing import List
2-
3-
41
def ways_to_make_change(total: int) -> int:
52
"""
63
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.
74
85
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.
96
"""
10-
# Cache to store computed results
117
cache = {}
12-
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1], cache)
8+
coins = (200, 100, 50, 20, 10, 5, 2, 1)
9+
return ways_to_make_change_helper(total, coins, 0, cache)
1310

1411

15-
def ways_to_make_change_helper(total: int, coins: List[int], cache: dict) -> int:
12+
def ways_to_make_change_helper(total: int, coins: tuple, coin_index: int, cache: dict) -> int:
1613
"""
1714
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1815
"""
19-
if total == 0 or len(coins) == 0:
16+
if total == 0 or coin_index >= len(coins):
2017
return 0
2118

22-
# Create cache key from current state
23-
cache_key = (total, tuple(coins))
19+
cache_key = (total, coin_index)
2420

2521
if cache_key in cache:
2622
return cache[cache_key]
2723

2824
ways = 0
29-
for coin_index in range(len(coins)):
30-
coin = coins[coin_index]
25+
for i in range(coin_index, len(coins)):
26+
coin = coins[i]
3127
count_of_coin = 1
3228
while coin * count_of_coin <= total:
3329
total_from_coins = coin * count_of_coin
3430
if total_from_coins == total:
3531
ways += 1
3632
else:
37-
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:], cache=cache)
33+
intermediate = ways_to_make_change_helper(total - total_from_coins, coins, i + 1, cache)
3834
ways += intermediate
3935
count_of_coin += 1
4036

41-
# Store result in cache
4237
cache[cache_key] = ways
4338
return ways

0 commit comments

Comments
 (0)