Skip to content

Commit 19df71f

Browse files
Optimize making_change: move base checks before cache lookup and add last-coin shortcut
1 parent 8b5f0b6 commit 19df71f

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed
Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,37 @@
11
from typing import List
22

33

4-
cache = {}
5-
coins = [200, 100, 50, 20, 10, 5, 2, 1]
4+
CACHE = {}
5+
COINS = [200, 100, 50, 20, 10, 5, 2, 1]
66

77

88
def ways_to_make_change(total: int) -> int:
99

10-
cache.clear()
10+
CACHE.clear()
1111
return ways_to_make_change_helper(total, 0)
1212

1313

1414
def ways_to_make_change_helper(total: int, coin_index: int) -> int:
15-
key = (total, coin_index)
16-
if key in cache:
17-
return cache[key]
18-
1915
if total == 0:
2016
return 1
21-
if coin_index >= len(coins) or total < 0:
17+
if coin_index >= len(COINS) or total < 0:
2218
return 0
19+
20+
# Optimization: if this is the last coin, check if total is divisible by it
21+
if coin_index == len(COINS) - 1:
22+
return 1 if total % COINS[coin_index] == 0 else 0
23+
24+
key = (total, coin_index)
25+
if key in CACHE:
26+
return CACHE[key]
2327

2428
ways = 0
25-
coin = coins[coin_index]
29+
coin = COINS[coin_index]
2630
count_of_coin = 0
2731

2832
while coin * count_of_coin <= total:
2933
ways += ways_to_make_change_helper(total - (coin * count_of_coin), coin_index + 1)
3034
count_of_coin += 1
3135

32-
cache[key] = ways
36+
CACHE[key] = ways
3337
return ways

0 commit comments

Comments
 (0)