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 = 4Output:
4Explanation:
There are 4 ways to make 4 using given coins:
[1, 1, 1, 1][1, 1, 2][2, 2][1, 3]
Example 2:
Input:
Output:
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 fromcointosum.dp[j] += dp[j - coin](Include current coin).
Time and Auxiliary Space Complexity
Expected Time Complexity:
O(N × sum), whereNis the number of coins.Expected Auxiliary Space Complexity:
O(sum), as we only store a 1D DP array.
Code (C++)
Code (Java)
Code (Python)
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