I am currently working through a book on algorithm design and came across a question whereby you must implement a greedy algorithm with dynamic programming to solve the coin change problem.
I was trying to implement this and I just can't figure out out or make sense of the algorithm given in my book. The algorithm is as follows(with my (lack of) understanding in comments) :
Change(p) {
C[0] = 0
for(i=1 to p) //cycling from 1 to the value of change we want, p
min = infinity
for(j=1 to k( //cyle from 1 to...?
if dj <=i then
if(1+C[i-dj] < min) then
min = 1+C[i-dj]
endif
endif
endfor
C[i] = min
endfor
return C[p]
}
And my attempt at interpreting what's going on :
/**
*
* @param d
* currency divisions
* @param p
* target
* @return number of coins
*/
public static int change(int[] d, int p) {
int[] tempArray = new int[Integer.MAX_VALUE]; // tempArray to store set
// of coins forming
// answer
for (int i = 1; i <= p; i++) { // cycling up to the wanted value
int min = Integer.MAX_VALUE; //assigning current minimum number of coints
for (int value : d) {//cycling through possible values
if (value < i) {
if (1 + tempArray[i - value] < min) { //if current value is less than min
min = 1 + tempArray[1 - value];//assign it
}
}
}
tempArray[i] = min; //assign min value to array of coins
}
System.out.println("help"); // :(
return tempArray[p];
}
Can someone please explain to me what I am missing, how to fix this, and how this algorithm is supposed to work? Dynamic Programming seems like such a useful tool, but I cannot get my head around it. I keep thinking recursively.
see this wikipedia link
an excerpt:
Greedy choice property We can make whatever choice seems best at the moment and then solve the subproblems that arise later. The choice made by a greedy algorithm may depend on choices made so far but not on future choices or all the solutions to the subproblem. It iteratively makes one greedy choice after another, reducing each given problem into a smaller one. In other words, a greedy algorithm never reconsiders its choices. This is the main difference from dynamic programming, which is exhaustive and is guaranteed to find the solution. After every stage, dynamic programming makes decisions based on all the decisions made in the previous stage, and may reconsider the previous stage's algorithmic path to solution.
Your code iterates through the int p
gets the optimum choice and puts it into the array tempArray
then uses this value to check the optimum choice in the next iteration.