14. Coin Change (Count Ways)
The problem can be found at the following link: Question Link
Problem Description
Given an integer array coins[] representing different denominations of currency and an integer sum, find the number of ways to make sum
using any number of coins.
πΉ Note: You have an infinite supply of each type of coin.
Examples
Example 1:
Input:
coins = [1, 2, 3], sum = 4
Output:
4
Explanation:
There are 4 ways to make 4
using given coins:
[1, 1, 1, 1]
[1, 1, 2]
[2, 2]
[1, 3]
Example 2:
Input:
coins = [2, 5, 3, 6], sum = 10
Output:
5
Explanation:
There are 5 ways to make 10
:
[2, 2, 2, 2, 2]
[2, 2, 3, 3]
[2, 2, 6]
[2, 3, 5]
[5, 5]
Constraints:
$1 \leq \text{Number of Coins} \leq 10^3$
$1 \leq \text{sum} \leq 10^6$
$1 \leq \text{coins}[i] \leq 10^3$
My Approach:
Optimized Dynamic Programming
Algorithm Steps:
Use a 1D DP array
dp[]
, wheredp[i]
stores the number of ways to make sumi
.Base Case:
dp[0] = 1
(There is one way to make sum0
: choose nothing).
Transition:
For each
coin
, update all sums fromcoin
tosum
.dp[j] += dp[j - coin]
(Include current coin).
Time and Auxiliary Space Complexity
Expected Time Complexity:
O(N Γ sum)
, whereN
is the number of coins.Expected Auxiliary Space Complexity:
O(sum)
, as we only store a 1D DP array.
Code (C++)
class Solution {
public:
int count(vector<int>& coins, int sum) {
vector<int> dp(sum + 1, 0);
dp[0] = 1;
for (int coin : coins)
for (int j = coin; j <= sum; j++)
dp[j] += dp[j - coin];
return dp[sum];
}
};
Code (Java)
class Solution {
public int count(int[] coins, int sum) {
int[] dp = new int[sum + 1];
dp[0] = 1;
for (int coin : coins)
for (int j = coin; j <= sum; j++)
dp[j] += dp[j - coin];
return dp[sum];
}
}
Code (Python)
class Solution:
def count(self, coins, sum):
dp = [0] * (sum + 1)
dp[0] = 1
for coin in coins:
for j in range(coin, sum + 1):
dp[j] += dp[j - coin]
return dp[sum]
Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated