πDay 12. Coin Change (Minimum Coins) π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Given an array coins[]
of distinct denominations and an integer sum
, determine the minimum number of coins required to make up the given sum.
You have an infinite supply of each type of coin.
If the sum cannot be formed, return -1
.
π Example Walkthrough:
Example 1:
Input:
coins[] = [25, 10, 5]
sum = 30
Output:
2
Explanation:
The minimum number of coins required is 2 (25 + 5).
Example 2:
Input:
coins[] = [9, 6, 5, 1]
sum = 19
Output:
3
Explanation:
The minimum number of coins required is 3 (9 + 9 + 1).
Example 3:
Input:
coins[] = [5, 1]
sum = 0
Output:
0
Explanation:
For a target sum of 0, no coins are needed.
Example 4:
Input:
coins[] = [4, 6, 2]
sum = 5
Output:
-1
Explanation:
It's not possible to obtain a sum of 5
using the given coins.
Constraints:
$(1 \leq \text{sum} \times \text{coins.size()} \leq 10^6)$
$(0 \leq \text{sum} \leq 10^4)$
$(1 \leq \text{coins}[i] \leq 10^4)$
$(1 \leq \text{coins.size()} \leq 10^3)$
π― My Approach:
Optimized Dynamic Programming
Algorithm Steps:
Define
dp[j]
as the minimum number of coins needed to obtainsum = j
.Base Case:
dp[0] = 0
(zero sum requires zero coins).Transition:
For each
coin
, updatedp[j]
for allj >= coin
using: $[ dp[j] = \min(dp[j], dp[j - coin] + 1) $]
Final Check: If
dp[sum] == β
, return-1
(sum cannot be formed).
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(N Γ sum), as we iterate over each coin and process all sums up to
sum
.Expected Auxiliary Space Complexity: O(sum), as we maintain a 1D DP array of size
sum + 1
.
π Solution Code
Code (C++)
class Solution {
public:
int minCoins(vector<int>& coins, int sum) {
vector<int> dp(sum + 1, INT_MAX);
dp[0] = 0;
for (int c : coins)
for (int j = c; j <= sum; j++)
if (dp[j - c] != INT_MAX)
dp[j] = min(dp[j], dp[j - c] + 1);
return dp[sum] == INT_MAX ? -1 : dp[sum];
}
};
Code (Java)
class Solution {
public int minCoins(int[] coins, int sum) {
int[] dp = new int[sum + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int c : coins)
for (int j = c; j <= sum; j++)
if (dp[j - c] != Integer.MAX_VALUE)
dp[j] = Math.min(dp[j], dp[j - c] + 1);
return dp[sum] == Integer.MAX_VALUE ? -1 : dp[sum];
}
}
Code (Python)
class Solution:
def minCoins(self, coins, sum):
dp = [float('inf')] * (sum + 1)
dp[0] = 0
for c in coins:
for j in range(c, sum + 1):
dp[j] = min(dp[j], dp[j - c] + 1)
return -1 if dp[sum] == float('inf') else 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