Skip to content

Commit c7979d5

Browse files
committed
refactor(ways_to_make_change): optimize cache keys with integer start_index
1 parent 391df35 commit c7979d5

1 file changed

Lines changed: 17 additions & 8 deletions

File tree

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

3+
# Defined once globally to avoid recreation overhead
4+
COINS = [200, 100, 50, 20, 10, 5, 2, 1]
5+
6+
37
# ===============> change function <============
48
def ways_to_make_change(total: int) -> int:
59
"""
@@ -9,36 +13,41 @@ def ways_to_make_change(total: int) -> int:
913
"""
1014
# Initialize a cache dictionary
1115
cache = {}
12-
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1], cache)
16+
# Passing 0 (the starting index) instead of the full list
17+
return ways_to_make_change_helper(total, 0, cache)
18+
1319

1420
# =================> change helper function <==============
15-
def ways_to_make_change_helper(total: int, coins: List[int], cache: dict) -> int:
21+
def ways_to_make_change_helper(total: int, start_index: int, cache: dict) -> int:
1622
"""
1723
Helper function for ways_to_make_change to avoid exposing the coins parameter to callers.
1824
"""
1925
# Create unique key for this subproblem
20-
cache_key = (total, tuple(coins))
26+
cache_key = (total, start_index)
2127

2228
# Return cached result if already calculated
2329
if cache_key in cache:
2430
return cache[cache_key]
2531

26-
if total == 0 or len(coins) == 0:
32+
if total == 0 or start_index >= len(COINS):
2733
return 0
2834

2935
ways = 0
30-
for coin_index in range(len(coins)):
31-
coin = coins[coin_index]
36+
# Iterate through the global COINS list using the integer index
37+
for i in range(start_index, len(COINS)):
38+
coin = COINS[i]
3239
count_of_coin = 1
3340
while coin * count_of_coin <= total:
3441
total_from_coins = coin * count_of_coin
3542
if total_from_coins == total:
3643
ways += 1
3744
else:
38-
intermediate = ways_to_make_change_helper(total - total_from_coins, coins=coins[coin_index+1:], cache=cache)
45+
# Just pass an integer (i + 1)
46+
intermediate = ways_to_make_change_helper(
47+
total - total_from_coins, start_index=i + 1, cache=cache
48+
)
3949
ways += intermediate
4050
count_of_coin += 1
4151

42-
# Save result before returning
4352
cache[cache_key] = ways
4453
return ways

0 commit comments

Comments
 (0)