Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

FACULTY OF ENGINEERING

Computer Engineering
3150703-Analysis & Design of Algorithms-Lab Manual

Experiment 8

Enrollment : Batch: Page no:


FACULTY OF ENGINEERING
Computer Engineering
3150703-Analysis & Design of Algorithms-Lab Manual

8. Implementation of making coin change problem using dynamic


programming.
Algorithm:
MAKING_COIN_CHANGE( C[n, N])

Step-1: For i ← 0 to n
SET c[i][0] = 0
Repeat step-2 to step-4 for the remaining matrix
values Step-2: For i ← 0 to n do
Step-3: For i ← 0 to n
do Step-4: If 𝑖 = 1 then
SET c[i][j] = 1 + c[1][j − d1]
Step-5: Else If 𝑗 < 𝑑𝑖 then
SET c[i][j] = c[i − 1][j]
Step-6: Else
SET c[i][j] = min (c[i − 1][j],1 + c[i][j − di])
Step-7: Return c[n, N]

Program:
#include <stdio.h>
void main()
{
int i, j, n, x, a[n];
printf("Enter number of coins:
"); scanf("%d", &n);
printf("Enter maximum value: ");
scanf("%d", &x);
printf("Enter value of each coin in sorted order:
"); for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}

int m[n][x + 1];


for (i = 0; i < n; i++)
{
for (j = 0; j < x + 1; j++)
{
if (j == 0) m[i]
[j] = 0;
else if (i == 0 && j < a[i] || i == 0 && j % a[i] != 0)
m[i][j] = -1;

Enrollment : Batch: Page no:


FACULTY OF ENGINEERING
Computer Engineering
3150703-Analysis & Design of Algorithms-Lab Manual

else if (i == 0 && m[i][j - a[i]] != -1)


m[i][j] = 1 + (m[i][j - a[i]]);

else if (j < a[i])


m[i][j] = m[i - 1][j];

else
{
if (m[i - 1][j] == -1 && m[i][j - a[i]] == -
1) m[i][j] = -1;

else if (m[i - 1][j] == -1 && m[i][j - a[i]] != -1)


m[i][j] = 1 + (m[i][j - a[i]]);

else if (m[i - 1][j] != -1 && m[i][j - a[i]] == -


1) m[i][j] = m[i - 1][j];

else
{
if ((1 + m[i][j - a[i]]) <= m[i - 1][j])
m[i][j] = 1 + (m[i][j - a[i]]);

else
m[i][j] = m[i - 1][j];
}
}
}
}
printf("\n\n\t");
for (j = 0; j < x + 1; j++)
{
printf("%d\t", j);
}
printf("\n");
for (i = 0; i < n; i++)
{
printf("%d\t", a[i]);

Enrollment : Batch: Page no:


FACULTY OF ENGINEERING
Computer Engineering
3150703-Analysis & Design of Algorithms-Lab Manual

for (j = 0; j < x + 1; j++)


{
if (m[i][j] == -1)
printf("0\t");
else
printf("%d\t", m[i][j]);
}
printf("\n");
}
printf("\nMinimum %d coins are required ", m[i - 1][j - 1]);
}

Output:

Time
complexity: Time Complexity = O(A^d), where d is the number of coins given

Enrollment : Batch: Page no:

You might also like