Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create CoinChange.java #390

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions JAVA/DYNAMIC_PROGRAMMING/CoinChange.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import java.util.Arrays;

public class CoinChange {

public static int coinChange(int[] coins, int amount) {
// Create a DP array initialized with a large value (infinity substitute)
int[] dp = new int[amount + 1];
Arrays.fill(dp, amount + 1);

// Base case: To make an amount of 0, we need 0 coins
dp[0] = 0;

// Fill the DP array
for (int i = 1; i <= amount; i++) {
for (int coin : coins) {
if (i - coin >= 0) {
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
}
}
}

// If we can't make the amount, return -1; otherwise, return dp[amount]
return dp[amount] > amount ? -1 : dp[amount];
}

public static void main(String[] args) {
int[] coins = {1, 2, 5};
int amount = 11;

int result = coinChange(coins, amount);
if (result == -1) {
System.out.println("It is not possible to make the amount with the given coins.");
} else {
System.out.println("The minimum number of coins needed: " + result);
}
}
}