Coin Change with Denominations

/**
You are given a total and an array of coin denominations. Find the minimum number of coins
required to make a change for the total and the set of coins that gave the minimum changes.
*/
import java.util.*;

public class CoinChangeWithDenominations{

/**
-print the coin denominations used for a change
- use the R array which holds the coin index
- repeatedly subtract the coin used until there is no more amount left
*/
public static void printCoins(int[] R, int[] coins){
System.out.println(Arrays.toString(coins));
System.out.println(Arrays.toString(R));
if(R[R.length-1]==-1){
System.out.println("no solutions possible");
return;
}

int start = R.length - 1;
while(start!=0){
int j = R[start];
System.out.println("Amount remaining: "+start+", coin used: "+coins[j]);
start = start - coins[j];
}

}
/**
-use array R to hold the coin index used to get a change, i.e. R[i] holds the index of coin used to get change for amount i
- use T array to hold the minimum number of coins needed for change, i.e. T[i] holds the minimum number of coins needed to find change for amount i
Time: O(amount*total_coins)
Space: O(amount)

REf: https://www.youtube.com/watch?v=NJuKJ8sasGk
*/
public static int getChanges(int[] coins, int total){
int[] T = new int[total+1];
int[] R = new int[total +1];
R[0] = 0;
T[0] = 0;
for(int i=1; i<=total; i++){
T[i] = Integer.MAX_VALUE -1;
R[i] = -1;
}
for(int j=0; j<coins.length; j++){
for(int i=1; i<=total; i++){
if(i>=coins[j]){
if((1+ T[i - coins[j]])<T[i]){
T[i] = 1 + T[i - coins[j]];
R[i] = j;
}
}
}
}
printCoins(R, coins);
return T[total];
}

public static void main(String[] args){
int[] coins = {7, 2, 3, 6};
int total = 4;
System.out.println(getChanges(coins, total));
}

}

No comments:

Post a Comment