Skip to content

Commit 59994df

Browse files
update making change
1 parent be7cc5a commit 59994df

1 file changed

Lines changed: 33 additions & 8 deletions

File tree

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,37 @@
1+
from typing import List
2+
3+
14
def ways_to_make_change(total: int) -> int:
2-
coins = [1, 2, 5, 10, 20, 50, 100, 200]
5+
6+
return ways_to_make_change_helper(total, [200, 100, 50, 20, 10, 5, 2, 1], coin_index = 0, cache = None)
7+
8+
9+
def ways_to_make_change_helper(total: int, coins: List[int], coin_index: int = 0, cache: dict = None) -> int:
10+
if cache == None:
11+
cache = {}
12+
13+
current_key = (total, coin_index)
14+
if current_key in cache:
15+
return cache[current_key]
316

4-
dp = [0] * (total + 1)
17+
if total == 0:
18+
return 1
519

6-
dp[0] = 1
20+
if coin_index == len(coins) - 1:
21+
return 1 if total % coins[coin_index] == 0 else 0
22+
23+
if total < 0 or coin_index >= len(coins):
24+
return 0
25+
26+
ways = 0
727

8-
for coin in coins:
9-
for i in range(coin, total + 1):
10-
dp[i] += dp[i - coin]
11-
12-
return dp[total]
28+
remaining_value = total - coins[coin_index]
29+
30+
taken_the_coin = ways_to_make_change_helper(remaining_value, coins, coin_index, cache)
31+
32+
left_the_coin = ways_to_make_change_helper(total, coins, coin_index + 1, cache)
33+
34+
ways = taken_the_coin + left_the_coin
35+
36+
cache[current_key] = ways
37+
return ways

0 commit comments

Comments
 (0)