Advertisement
jakaria_hossain

Coin change using 2D array

Oct 23rd, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main()
  4. {
  5. int i,n,k=0;
  6. printf("How many coin do you have?\n");
  7. scanf("%d",&n);
  8. int array[n+1],arr[n];
  9. printf("Enter coins\n");
  10. for(i=0;i<n;i++)scanf("%d",&array[i]);
  11. printf("Enter amount\n");
  12. int taka;
  13. scanf("%d",&taka);
  14. int table[n+1][taka+2],j;
  15. for(i=0;i<n;i++)
  16. {
  17. for(j=0;j<=taka;j++)
  18. {
  19. if(i==0)table[i][j]=j/array[i];
  20. else
  21. {
  22. if(table[i-1][j]<(j/array[i]+table[i-1][j%array[i]]))table[i][j]=table[i-1][j];
  23. else table[i][j]=j/array[i]+table[i-1][j%array[i]];
  24. }
  25. }
  26. }
  27. i=n-1,j=taka;
  28. while(i>=0 && j>=0 && table[i][j]!=0)
  29. {
  30. if(table[i][j]!=table[i-1][j])
  31. {
  32. arr[k++]=array[i];
  33. j=j-array[i];
  34. }
  35. else i--;
  36. }
  37. printf("\nRequired minimum coins = %d\n",table[n-1][taka]);
  38. printf("Coins are\n");
  39. for(k=k-1;k>=0;k--)printf("%d ",arr[k]);
  40.  
  41. return 0;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement