Professional Documents
Culture Documents
Lecture On Coin Changing Slides
Lecture On Coin Changing Slides
U S
IT
TH
Y
O F
H
G
E
R
D I U
N B
Coin Changing
Javier Esparza
Computer Science
School of Informatics
The University of Edinburgh
This study source was downloaded by 100000819922722 from CourseHero.com on 05-25-2022 16:58:31 GMT -05:00
1
The problem
This study source was downloaded by 100000819922722 from CourseHero.com on 05-25-2022 16:58:31 GMT -05:00
2
The divide-and-conquer approach
Do not use c0. In this case we just need to know the number of
coins needed to change a using c1, . . . ck−1.
This study source was downloaded by 100000819922722 from CourseHero.com on 05-25-2022 16:58:31 GMT -05:00
3
• Termination guarantee:
– The parameter (a + k), always decreases for either of the steps
(use c0 or not), and it cannot decrease for ever without reaching
one of the basis cases.
This study source was downloaded by 100000819922722 from CourseHero.com on 05-25-2022 16:58:31 GMT -05:00
4
class Change {
private static int[] c;
This study source was downloaded by 100000819922722 from CourseHero.com on 05-25-2022 16:58:31 GMT -05:00
5
The greedy strategy
Always try to give as many large coins as possible before considering
smaller coins.
This study source was downloaded by 100000819922722 from CourseHero.com on 05-25-2022 16:58:31 GMT -05:00
6
public static int change(int amount, int[] coins){
int[][] tab = new int[amount+1][coins.length+1];
This study source was downloaded by 100000819922722 from CourseHero.com on 05-25-2022 16:58:31 GMT -05:00
7
tab[0]=0;
for(int i = 1; i <= amount; i++) {
tab[i] = Integer.MAX_VALUE;
for(int j = coins.length-1; j >= 0 ; j--) {
if (i >= coins[j]){
int c = 1 + tab[i-coins[j]];
if (c < tab[i]) tab[i] = c;
}
}
}
return(tab[amount]);
}
This study source was downloaded by 100000819922722 from CourseHero.com on 05-25-2022 16:58:31 GMT -05:00
8
tab[0]=0;
for(int i = 1; i <= amount; i++) {
tab[i%k] = Integer.MAX_VALUE;
for(int j = coins.length-1; j >= 0 ; j--) {
if (i >= coins[j]){
int c = 1 + tab[(i-coins[j])%k];
if (c < tab[i%k]) tab[i%k] = c;
}
}
}
return(tab[amount%k]);
}
This study source was downloaded by 100000819922722 from CourseHero.com on 05-25-2022 16:58:31 GMT -05:00
Powered by TCPDF (www.tcpdf.org)