Skip to content

Solved DP-1#1986

Open
pratul2789 wants to merge 1 commit intosuper30admin:masterfrom
pratul2789:master
Open

Solved DP-1#1986
pratul2789 wants to merge 1 commit intosuper30admin:masterfrom
pratul2789:master

Conversation

@pratul2789
Copy link

No description provided.

@super30admin
Copy link
Owner

Your DP solution for the coin change problem is correct and efficient. Well done! However, there are a few areas for improvement:

  • Avoid using magic numbers like 999999. Instead, you can use float('inf') or initialize with amount+1 (since the maximum number of coins needed is at most amount if using coins of 1). For example, dp = [amount+1] * (amount+1) and then check if dp[-1] == amount+1 to return -1. This is more robust and readable.
  • The comments in the code are a bit confusing. You have comments that refer to a 2D DP approach (e.g., "same column, one row above"), but you are using a 1D DP. It's better to remove outdated comments to avoid confusion.
  • The inner loop in the DP solution can be optimized by starting from coins[i] to avoid the condition check inside. Instead of iterating from 1 to amount and then checking if j >= coins[i], you can iterate from coins[i] to amount. This might slightly improve performance.

Example improvement:

dp = [amount+1] * (amount+1)
dp[0] = 0
for coin in coins:
    for j in range(coin, amount+1):
        dp[j] = min(dp[j], 1 + dp[j-coin])

This is cleaner and avoids the inner condition.

Also, note that the problem states that if the amount is 0, return 0. Your solution handles that correctly because dp[0]=0.

Overall, your solution is good, but with minor improvements it can be more professional and readable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants