Skip to content

Commit 61191b2

Browse files
committed
Optimize cache by using start_index instead of coin sub-arrays
1 parent 7e20d44 commit 61191b2

1 file changed

Lines changed: 8 additions & 7 deletions

File tree

‎Sprint-2/improve_with_caches/making_change/making_change.py‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,27 @@
11
from typing import List
2+
COINS = [200, 100, 50, 20, 10, 5, 2, 1]
23

34
cache = {}
45

56
def ways_to_make_change(total: int) -> int:
6-
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1])
7+
return ways_to_make_change_helper(total, 0)
78

89

9-
def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
10-
key = (total, tuple(coins))
10+
def ways_to_make_change_helper(total: int, start_index: int) -> int:
11+
key = (total, start_index)
1112

1213
if key in cache:
1314
return cache[key]
1415

1516
if total == 0:
1617
return 1
1718

18-
if total < 0 or len(coins) == 0:
19+
if total < 0 or start_index >= len(COINS):
1920
return 0
2021

2122
ways = 0
22-
for coin_index in range(len(coins)):
23-
coin = coins[coin_index]
23+
for coin_index in range(start_index, len(COINS)):
24+
coin = COINS[coin_index]
2425
count_of_coin = 1
2526
while coin * count_of_coin <= total:
2627
total_from_coins = coin * count_of_coin
@@ -29,7 +30,7 @@ def ways_to_make_change_helper(total: int, coins: List[int]) -> int:
2930
else:
3031
ways += ways_to_make_change_helper(
3132
total - total_from_coins,
32-
coins=coins[coin_index + 1:]
33+
coin_index + 1
3334
)
3435
count_of_coin += 1
3536

0 commit comments

Comments
 (0)