11.Coin Change
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
To solve this problem, I use dynamic programming. I create a 2D DP array dp
where dp[i][s]
represents the number of ways to make the sum s
using the first i
coins. I initialize dp[0][s]
with 1
if s
is divisible by the value of the first coin as base case.
Then, I iterate through the coins and the target sum. For each combination, I calculate two possibilities:
Not taking the current coin (nottake = dp[i - 1][s]
)
Taking the current coin (take = dp[i][s - coins[i]]
if s - coins[i] >= 0
)
The total number of ways to make the sum s
using the first i
coins is dp[i][s] = take + nottake
.
Consider the example coins = [1, 2, 3]
, N = 3
, and sum = 4
. The DP table would look like this:
0
1
1
1
1
1
1
1
1
2
2
3
2
1
1
2
3
4
The value at dp[2][4]
represents the number of ways to make the sum 4 using coins [1, 2, 3]
, which is 4.
Time Complexity: O(N * sum)
, where N
is the number of coins and sum
is the given target sum.
Auxiliary Space Complexity: O(N * sum)
, as we use a 2D DP array to store intermediate results.
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.