Skip to content

Commit e3bc298

Browse files
Coin Change Better Solution (DP)
1 parent 1f77b84 commit e3bc298

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

0322-Coin-Change.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,19 @@ def coinChange(self, coins: List[int], amount: int) -> int:
4747
for j in range(len(coins)):
4848
if coins[j] <= i:
4949
dp[i] = min(dp[i], 1 + dp[i - coins[j]])
50+
return -1 if dp[amount] > amount else dp[amount]
51+
52+
# Slightly optimised for average case
53+
54+
class Solution:
55+
def coinChange(self, coins: List[int], amount: int) -> int:
56+
coins.sort()
57+
dp = [amount + 1 for _ in range(amount + 1)]
58+
dp[0] = 0
59+
for i in range(amount + 1):
60+
for j in range(len(coins)):
61+
if coins[j] <= i:
62+
dp[i] = min(dp[i], 1 + dp[i - coins[j]])
63+
else:
64+
break
5065
return -1 if dp[amount] > amount else dp[amount]

0 commit comments

Comments
 (0)