0

I am having a problem with writing a dynamic algorithm to solve coin change problem what I got is this:

arr[value] - a global array filled with 0, lenght of the value I want to solve;

a[n] - an array with coin values;

void dynamic(int n, int *a, int value) {
arr[0]=0;
for(int i=1;i<value;i++){;
    for(int j=0;j<n;j++){
        if(i==arr[j]) arr[i]=1;
        else{
            arr[i] = arr[i-1] + 1;          
        }
    }
}}

I know how I want to do this but, I don't know how to implement it.

Example:
Let's say I have coins 1 4 10 15 40 and value 37 to solve. I am filling arr like this:
if coin value = i I do arr[i] = 1; for next elements as long as i is lower than next coin I put previous value+1, arr[i-1] + 1.
So this should fill arr[i] like this 1 = 1, 2 = 2, 3 = 3, 4 = 1, 5 = 2 and so on but I am missing some thing and don't know how to fill it right the way I want.

Can somebody help do it the way I want ? I've been trying to figure out it but nothing I found is correct. I even wrote the whole algorithm using recursion but it's too slow so I need to write it all over again.

asheeshr
  • 4,088
  • 6
  • 31
  • 50
Paul
  • 163
  • 7
  • 2
    Sounds like homework. You're dealing with the Knapsack problem. It will always be slow for any 'large' input: http://en.wikipedia.org/wiki/Knapsack_Problem – Marc B Mar 16 '11 at 17:06
  • It's not a homework if it would be I'd not write it again the way I want. – Paul Mar 16 '11 at 17:08
  • 1
    Related SO question: http://stackoverflow.com/questions/1518330/coin-change-problem-with-infinite-number-of-coins-of-each-denomination – AJG85 Mar 16 '11 at 17:48

1 Answers1

0

You might want:

memset(arr,0,sizeof(arr));
arr[0]=1;
for(int i=0;i<n;++i)
    for(int j=a[i];j<value;++j)
        arr[j]+=arr[j-a[i]];

This ought to be correct if I understand you right, basically it's a neat trick to implement the recursion...

f[i,j]=f[i-1,j]+f[i-1,j-a[i]];

Obviously this takes O(n Value) time.

phoeagon
  • 2,080
  • 17
  • 20