SlideShare a Scribd company logo
1 of 11
Download to read offline
Coin Change Problem
  Finding the number of ways of making changes
for a particular amount of cents, n, using a given
set of denominations C={c1…cd} (e.g, the US
coin system: {1, 5, 10, 25, 50, 100})
–  An example: n = 4,C = {1,2,3}, solutions: {1,1,1,1},
{1,1,2},{2,2},{1,3}.
  Minimizing the number of coins returned for a
particular quantity of change (available coins
{1, 5, 10, 25})
–  30 Cents (solution: 25 + 2, two coins)
–  67 Cents ?
  17 cents given denominations = {1, 2, 3, 4}?
Sudoku Puzzle
Find the Fewest Coins:
Casher’s algorithm
  Given 30 cents, and coins {1, 5, 10, 25}
  Here is what a casher will do: always go with
coins of highest value first
–  Choose the coin with highest value 25
•  1 quarter
–  Now we have 5 cents left
•  1 nickel
The solution is: 2 (one quarter + one nickel)
Greedy Algorithm Does not
Always Give Optimal Solution to
Coin Change Problem
  Coins = {1, 3, 4, 5}
  7 cents = ?
  Coins = {1, 3, 4, 5}
  7 cents = ?
  Greedy solution:
–  3 coins: one 5 + two 1
  Optimal solution:
–  2 coins: one 3 + one 4
Find the Fewest Coins:
Divide and Conquer
  30 cents, given coins {1, 5, 10, 25, 50}, we need
to calculate MinChange(30)
  Choose the smallest of the following:
–  1 + MinChange(29) #give a penny
–  1 + MinChange(25) #give a nickel
–  1 + MinChange(10) #give a dime
–  1 + MinChange(5) #give a quarter
  Do not know MinChange(29), MinChange(25),
MinChange(10), MinChange(5)?
Coin Change Problem: A Recursive
Algorithm
1.  MinChange(M)
2.  if M = 0
3.  return 0
4.  v  ∞
5.  for c in denominations ≤ M
6.  v  min {MinChange(M-c) + 1, v}
7.  return v
Recursive Algorithm Is Not Efficient
  It recalculates the optimal coin combination for a
given amount of money repeatedly
30
29 25 5
2428 4
1
5 25
27
26
25
20
How to avoid computing the same
function multiple times
  We’re re-computing values in our algorithm
more than once
  Save results of each computation for 0 to M
  This way, we can do a reference call to find an
already computed value, instead of re-
computing each time
  Running time M*d, where M is the value of
money and d is the number of denominations
Coin Change Problem: Save the
Intermediate Results
1.  MinChange(M)
2.  if minChange[M] not empty
3.  return minChange[M]
4.  if M = 0
5.  return 0
6.  for c in denominations ≤ M
7.  v  min {MinChange(M-c) + 1, v}
8.  minChange[M] = v
9.  return v
The Change Problem: Dynamic
Programming
1.  MinChangeDP(M)
2.  minCoin[0]  0
3.  for m  1 to M
4.  minCoin[m] infinity
5.  for c in denominations ≤ M
6.  if minCoin[m-c] + 1 < minCoin[m]
7.  minCoin[m]minCoin[m-c] + 1
8.  return minCoin[M]
Proof:
Let N be the amount to be paid. Let the optimal solution be P=A*10 + B*5 +
C. Clearly B≤1 (otherwise we can decrease B by 2 and increase A by 1,
improving the solution). Similarly, C≤4.
Let the solution given by GreedyCoinChange be P=a*10 + b*5 + c. Clearly
b≤1 (otherwise the algorithm would output 10 instead of 5). Similarly c≤4.
From 0≤ C≤4 and P=(2A+B)*5+C we have C=P mod 5.
Similarly c=P mod 5, and hence c=C. Let Q=(P-C)/5.
From 0≤ B≤ 1 and Q = 2A + B we have B=Q mod 2.
Similarly b=Q mod 2, and hence b=B.
Thus a=A, b=B, c=C, i.e., the solution given by GreedyCoinChange is
optimal.
Greedy algorithm outputs optimal
solutions for coin values 10, 5, 1

More Related Content

What's hot (20)

Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
P, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-HardP, NP, NP-Complete, and NP-Hard
P, NP, NP-Complete, and NP-Hard
 
Unit 1 chapter 1 Design and Analysis of Algorithms
Unit 1   chapter 1 Design and Analysis of AlgorithmsUnit 1   chapter 1 Design and Analysis of Algorithms
Unit 1 chapter 1 Design and Analysis of Algorithms
 
Dinive conquer algorithm
Dinive conquer algorithmDinive conquer algorithm
Dinive conquer algorithm
 
Ch04
Ch04Ch04
Ch04
 
Backtracking & branch and bound
Backtracking & branch and boundBacktracking & branch and bound
Backtracking & branch and bound
 
5 csp
5 csp5 csp
5 csp
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1
 
Np hard
Np hardNp hard
Np hard
 
Divide and conquer - Quick sort
Divide and conquer - Quick sortDivide and conquer - Quick sort
Divide and conquer - Quick sort
 
Daa notes 1
Daa notes 1Daa notes 1
Daa notes 1
 
Asymptotic Notations
Asymptotic NotationsAsymptotic Notations
Asymptotic Notations
 
Asymptotic notation
Asymptotic notationAsymptotic notation
Asymptotic notation
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Data Structure and Algorithm - Divide and Conquer
Data Structure and Algorithm - Divide and ConquerData Structure and Algorithm - Divide and Conquer
Data Structure and Algorithm - Divide and Conquer
 
Design and Analysis of Algorithms
Design and Analysis of AlgorithmsDesign and Analysis of Algorithms
Design and Analysis of Algorithms
 
Chapter 5 Syntax Directed Translation
Chapter 5   Syntax Directed TranslationChapter 5   Syntax Directed Translation
Chapter 5 Syntax Directed Translation
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptx
 
Design and analysis of algorithms
Design and analysis of algorithmsDesign and analysis of algorithms
Design and analysis of algorithms
 
Loop invarient
Loop invarientLoop invarient
Loop invarient
 

Viewers also liked

Coin box
Coin boxCoin box
Coin boxklecoq
 
1.3 Описательная статистика
1.3 Описательная статистика1.3 Описательная статистика
1.3 Описательная статистикаDEVTYPE
 
Dynamic Programming - Matrix Chain Multiplication
Dynamic Programming - Matrix Chain MultiplicationDynamic Programming - Matrix Chain Multiplication
Dynamic Programming - Matrix Chain MultiplicationPecha Inc.
 
Pascal's Triangle slideshow
Pascal's Triangle slideshowPascal's Triangle slideshow
Pascal's Triangle slideshowecooperms
 
Pascal’s triangle and its applications and properties
Pascal’s triangle and its applications and propertiesPascal’s triangle and its applications and properties
Pascal’s triangle and its applications and propertiesJordan Leong
 
Counting money
Counting moneyCounting money
Counting moneylkarol923
 
Intro to Coins Interactive Powerpoint
Intro to Coins Interactive PowerpointIntro to Coins Interactive Powerpoint
Intro to Coins Interactive Powerpointrevordm
 
Pascals Triangle
Pascals TrianglePascals Triangle
Pascals TrianglePeteDom1234
 

Viewers also liked (9)

Coin box
Coin boxCoin box
Coin box
 
1.3 Описательная статистика
1.3 Описательная статистика1.3 Описательная статистика
1.3 Описательная статистика
 
Dynamic Programming - Matrix Chain Multiplication
Dynamic Programming - Matrix Chain MultiplicationDynamic Programming - Matrix Chain Multiplication
Dynamic Programming - Matrix Chain Multiplication
 
Pascal's Triangle slideshow
Pascal's Triangle slideshowPascal's Triangle slideshow
Pascal's Triangle slideshow
 
Pascal’s triangle and its applications and properties
Pascal’s triangle and its applications and propertiesPascal’s triangle and its applications and properties
Pascal’s triangle and its applications and properties
 
Counting money
Counting moneyCounting money
Counting money
 
Pascal Triangle
Pascal TrianglePascal Triangle
Pascal Triangle
 
Intro to Coins Interactive Powerpoint
Intro to Coins Interactive PowerpointIntro to Coins Interactive Powerpoint
Intro to Coins Interactive Powerpoint
 
Pascals Triangle
Pascals TrianglePascals Triangle
Pascals Triangle
 

Similar to Coin Change Problem

Coin change using dp
Coin change using dpCoin change using dp
Coin change using dparfin97
 
A study on number theory and its applications
A study on number theory and its applicationsA study on number theory and its applications
A study on number theory and its applicationsItishree Dash
 
Greedy + Divide & Conquer
Greedy + Divide &  ConquerGreedy + Divide &  Conquer
Greedy + Divide & Conquervsccreations1
 
Math-tanong CEER 2012 - Set 1 Solutions
Math-tanong CEER 2012 - Set 1 SolutionsMath-tanong CEER 2012 - Set 1 Solutions
Math-tanong CEER 2012 - Set 1 SolutionsGilbert Joseph Abueg
 
Math-tanong CEER 2012 - Set 1 solutions
Math-tanong CEER 2012 - Set 1 solutionsMath-tanong CEER 2012 - Set 1 solutions
Math-tanong CEER 2012 - Set 1 solutionsGilbert Joseph Abueg
 
Simultaneous Equations Practical Construction
Simultaneous Equations Practical ConstructionSimultaneous Equations Practical Construction
Simultaneous Equations Practical ConstructionDaniel Ross
 
9 - DynamicProgramming-plus latihan.ppt
9 - DynamicProgramming-plus latihan.ppt9 - DynamicProgramming-plus latihan.ppt
9 - DynamicProgramming-plus latihan.pptKerbauBakar
 
Calculating Mine Probability in Minesweeper
Calculating Mine Probability in MinesweeperCalculating Mine Probability in Minesweeper
Calculating Mine Probability in MinesweeperLukeVideckis
 
Matrix chain multiplication in design analysis of algorithm
Matrix chain multiplication in design analysis of algorithmMatrix chain multiplication in design analysis of algorithm
Matrix chain multiplication in design analysis of algorithmRajKumar323561
 
Computer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdfComputer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdfjannatulferdousmaish
 
CSE1107 Chinese Remainder Theorem in Discrete Mathmatics.pptx
CSE1107 Chinese Remainder Theorem in Discrete Mathmatics.pptxCSE1107 Chinese Remainder Theorem in Discrete Mathmatics.pptx
CSE1107 Chinese Remainder Theorem in Discrete Mathmatics.pptxgbikorno
 
No factorization,no complex methods -Simplest method to solve quadratic equa...
No factorization,no complex methods -Simplest method to solve  quadratic equa...No factorization,no complex methods -Simplest method to solve  quadratic equa...
No factorization,no complex methods -Simplest method to solve quadratic equa...FabMarks
 
Consider the following polynomials
Consider the following polynomialsConsider the following polynomials
Consider the following polynomialsTutorMate33
 
Applied mathematics for soil science Lecture No 2Scientific Notions.pdf
Applied mathematics for soil science Lecture No 2Scientific Notions.pdfApplied mathematics for soil science Lecture No 2Scientific Notions.pdf
Applied mathematics for soil science Lecture No 2Scientific Notions.pdfMoe Ameen
 
Introduction to Dynamic Programming.pptx
Introduction to Dynamic Programming.pptxIntroduction to Dynamic Programming.pptx
Introduction to Dynamic Programming.pptxPochupouOwo
 
Appendix a 2
Appendix a 2Appendix a 2
Appendix a 2Loc Tran
 
Data structure notes
Data structure notesData structure notes
Data structure notesanujab5
 

Similar to Coin Change Problem (20)

Coin change using dp
Coin change using dpCoin change using dp
Coin change using dp
 
A study on number theory and its applications
A study on number theory and its applicationsA study on number theory and its applications
A study on number theory and its applications
 
Greedy + Divide & Conquer
Greedy + Divide &  ConquerGreedy + Divide &  Conquer
Greedy + Divide & Conquer
 
Math-tanong CEER 2012 - Set 1 Solutions
Math-tanong CEER 2012 - Set 1 SolutionsMath-tanong CEER 2012 - Set 1 Solutions
Math-tanong CEER 2012 - Set 1 Solutions
 
Math-tanong CEER 2012 - Set 1 solutions
Math-tanong CEER 2012 - Set 1 solutionsMath-tanong CEER 2012 - Set 1 solutions
Math-tanong CEER 2012 - Set 1 solutions
 
Daa chapter 3
Daa chapter 3Daa chapter 3
Daa chapter 3
 
Simultaneous Equations Practical Construction
Simultaneous Equations Practical ConstructionSimultaneous Equations Practical Construction
Simultaneous Equations Practical Construction
 
Chapter 10
Chapter 10Chapter 10
Chapter 10
 
9 - DynamicProgramming-plus latihan.ppt
9 - DynamicProgramming-plus latihan.ppt9 - DynamicProgramming-plus latihan.ppt
9 - DynamicProgramming-plus latihan.ppt
 
Calculating Mine Probability in Minesweeper
Calculating Mine Probability in MinesweeperCalculating Mine Probability in Minesweeper
Calculating Mine Probability in Minesweeper
 
Matrix chain multiplication in design analysis of algorithm
Matrix chain multiplication in design analysis of algorithmMatrix chain multiplication in design analysis of algorithm
Matrix chain multiplication in design analysis of algorithm
 
Computer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdfComputer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdf
 
CSE1107 Chinese Remainder Theorem in Discrete Mathmatics.pptx
CSE1107 Chinese Remainder Theorem in Discrete Mathmatics.pptxCSE1107 Chinese Remainder Theorem in Discrete Mathmatics.pptx
CSE1107 Chinese Remainder Theorem in Discrete Mathmatics.pptx
 
No factorization,no complex methods -Simplest method to solve quadratic equa...
No factorization,no complex methods -Simplest method to solve  quadratic equa...No factorization,no complex methods -Simplest method to solve  quadratic equa...
No factorization,no complex methods -Simplest method to solve quadratic equa...
 
Consider the following polynomials
Consider the following polynomialsConsider the following polynomials
Consider the following polynomials
 
Lec39
Lec39Lec39
Lec39
 
Applied mathematics for soil science Lecture No 2Scientific Notions.pdf
Applied mathematics for soil science Lecture No 2Scientific Notions.pdfApplied mathematics for soil science Lecture No 2Scientific Notions.pdf
Applied mathematics for soil science Lecture No 2Scientific Notions.pdf
 
Introduction to Dynamic Programming.pptx
Introduction to Dynamic Programming.pptxIntroduction to Dynamic Programming.pptx
Introduction to Dynamic Programming.pptx
 
Appendix a 2
Appendix a 2Appendix a 2
Appendix a 2
 
Data structure notes
Data structure notesData structure notes
Data structure notes
 

More from DEVTYPE

Рукописные лекции по линейной алгебре
Рукописные лекции по линейной алгебреРукописные лекции по линейной алгебре
Рукописные лекции по линейной алгебреDEVTYPE
 
1.4 Точечные оценки и их свойства
1.4 Точечные оценки и их свойства1.4 Точечные оценки и их свойства
1.4 Точечные оценки и их свойстваDEVTYPE
 
1.2 Выборка. Выборочное пространство
1.2 Выборка. Выборочное пространство1.2 Выборка. Выборочное пространство
1.2 Выборка. Выборочное пространствоDEVTYPE
 
Continuity and Uniform Continuity
Continuity and Uniform ContinuityContinuity and Uniform Continuity
Continuity and Uniform ContinuityDEVTYPE
 
Recurrences
RecurrencesRecurrences
RecurrencesDEVTYPE
 
D-кучи и их применение
D-кучи и их применениеD-кучи и их применение
D-кучи и их применениеDEVTYPE
 
Диаграммы Юнга, плоские разбиения и знакочередующиеся матрицы
Диаграммы Юнга, плоские разбиения и знакочередующиеся матрицыДиаграммы Юнга, плоские разбиения и знакочередующиеся матрицы
Диаграммы Юнга, плоские разбиения и знакочередующиеся матрицыDEVTYPE
 
ЖАДНЫЕ АЛГОРИТМЫ
ЖАДНЫЕ АЛГОРИТМЫ ЖАДНЫЕ АЛГОРИТМЫ
ЖАДНЫЕ АЛГОРИТМЫ DEVTYPE
 
Скорость роста функций
Скорость роста функцийСкорость роста функций
Скорость роста функцийDEVTYPE
 
Asymptotic Growth of Functions
Asymptotic Growth of FunctionsAsymptotic Growth of Functions
Asymptotic Growth of FunctionsDEVTYPE
 
Кучи
КучиКучи
КучиDEVTYPE
 
Кодирование Хаффмана
Кодирование ХаффманаКодирование Хаффмана
Кодирование ХаффманаDEVTYPE
 
Жадные алгоритмы: введение
Жадные алгоритмы: введениеЖадные алгоритмы: введение
Жадные алгоритмы: введениеDEVTYPE
 
Разбор задач по дискретной вероятности
Разбор задач по дискретной вероятностиРазбор задач по дискретной вероятности
Разбор задач по дискретной вероятностиDEVTYPE
 
Разбор задач модуля "Теория графов ll"
Разбор задач модуля "Теория графов ll"Разбор задач модуля "Теория графов ll"
Разбор задач модуля "Теория графов ll"DEVTYPE
 
Наибольший общий делитель
Наибольший общий делительНаибольший общий делитель
Наибольший общий делительDEVTYPE
 
Числа Фибоначчи
Числа ФибоначчиЧисла Фибоначчи
Числа ФибоначчиDEVTYPE
 
О-символика
О-символикаО-символика
О-символикаDEVTYPE
 
Зачем изучать алгоритмы?
Зачем изучать алгоритмы?Зачем изучать алгоритмы?
Зачем изучать алгоритмы?DEVTYPE
 
Разбор задач пятого модуля
Разбор задач пятого модуляРазбор задач пятого модуля
Разбор задач пятого модуляDEVTYPE
 

More from DEVTYPE (20)

Рукописные лекции по линейной алгебре
Рукописные лекции по линейной алгебреРукописные лекции по линейной алгебре
Рукописные лекции по линейной алгебре
 
1.4 Точечные оценки и их свойства
1.4 Точечные оценки и их свойства1.4 Точечные оценки и их свойства
1.4 Точечные оценки и их свойства
 
1.2 Выборка. Выборочное пространство
1.2 Выборка. Выборочное пространство1.2 Выборка. Выборочное пространство
1.2 Выборка. Выборочное пространство
 
Continuity and Uniform Continuity
Continuity and Uniform ContinuityContinuity and Uniform Continuity
Continuity and Uniform Continuity
 
Recurrences
RecurrencesRecurrences
Recurrences
 
D-кучи и их применение
D-кучи и их применениеD-кучи и их применение
D-кучи и их применение
 
Диаграммы Юнга, плоские разбиения и знакочередующиеся матрицы
Диаграммы Юнга, плоские разбиения и знакочередующиеся матрицыДиаграммы Юнга, плоские разбиения и знакочередующиеся матрицы
Диаграммы Юнга, плоские разбиения и знакочередующиеся матрицы
 
ЖАДНЫЕ АЛГОРИТМЫ
ЖАДНЫЕ АЛГОРИТМЫ ЖАДНЫЕ АЛГОРИТМЫ
ЖАДНЫЕ АЛГОРИТМЫ
 
Скорость роста функций
Скорость роста функцийСкорость роста функций
Скорость роста функций
 
Asymptotic Growth of Functions
Asymptotic Growth of FunctionsAsymptotic Growth of Functions
Asymptotic Growth of Functions
 
Кучи
КучиКучи
Кучи
 
Кодирование Хаффмана
Кодирование ХаффманаКодирование Хаффмана
Кодирование Хаффмана
 
Жадные алгоритмы: введение
Жадные алгоритмы: введениеЖадные алгоритмы: введение
Жадные алгоритмы: введение
 
Разбор задач по дискретной вероятности
Разбор задач по дискретной вероятностиРазбор задач по дискретной вероятности
Разбор задач по дискретной вероятности
 
Разбор задач модуля "Теория графов ll"
Разбор задач модуля "Теория графов ll"Разбор задач модуля "Теория графов ll"
Разбор задач модуля "Теория графов ll"
 
Наибольший общий делитель
Наибольший общий делительНаибольший общий делитель
Наибольший общий делитель
 
Числа Фибоначчи
Числа ФибоначчиЧисла Фибоначчи
Числа Фибоначчи
 
О-символика
О-символикаО-символика
О-символика
 
Зачем изучать алгоритмы?
Зачем изучать алгоритмы?Зачем изучать алгоритмы?
Зачем изучать алгоритмы?
 
Разбор задач пятого модуля
Разбор задач пятого модуляРазбор задач пятого модуля
Разбор задач пятого модуля
 

Recently uploaded

development of diagnostic enzyme assay to detect leuser virus
development of diagnostic enzyme assay to detect leuser virusdevelopment of diagnostic enzyme assay to detect leuser virus
development of diagnostic enzyme assay to detect leuser virusNazaninKarimi6
 
GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)Areesha Ahmad
 
Human & Veterinary Respiratory Physilogy_DR.E.Muralinath_Associate Professor....
Human & Veterinary Respiratory Physilogy_DR.E.Muralinath_Associate Professor....Human & Veterinary Respiratory Physilogy_DR.E.Muralinath_Associate Professor....
Human & Veterinary Respiratory Physilogy_DR.E.Muralinath_Associate Professor....muralinath2
 
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdfPests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdfPirithiRaju
 
Pests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdfPests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdfPirithiRaju
 
Introduction to Viruses
Introduction to VirusesIntroduction to Viruses
Introduction to VirusesAreesha Ahmad
 
Locating and isolating a gene, FISH, GISH, Chromosome walking and jumping, te...
Locating and isolating a gene, FISH, GISH, Chromosome walking and jumping, te...Locating and isolating a gene, FISH, GISH, Chromosome walking and jumping, te...
Locating and isolating a gene, FISH, GISH, Chromosome walking and jumping, te...Silpa
 
Connaught Place, Delhi Call girls :8448380779 Model Escorts | 100% verified
Connaught Place, Delhi Call girls :8448380779 Model Escorts | 100% verifiedConnaught Place, Delhi Call girls :8448380779 Model Escorts | 100% verified
Connaught Place, Delhi Call girls :8448380779 Model Escorts | 100% verifiedDelhi Call girls
 
9999266834 Call Girls In Noida Sector 22 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 22 (Delhi) Call Girl Service9999266834 Call Girls In Noida Sector 22 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 22 (Delhi) Call Girl Servicenishacall1
 
Factory Acceptance Test( FAT).pptx .
Factory Acceptance Test( FAT).pptx       .Factory Acceptance Test( FAT).pptx       .
Factory Acceptance Test( FAT).pptx .Poonam Aher Patil
 
Grade 7 - Lesson 1 - Microscope and Its Functions
Grade 7 - Lesson 1 - Microscope and Its FunctionsGrade 7 - Lesson 1 - Microscope and Its Functions
Grade 7 - Lesson 1 - Microscope and Its FunctionsOrtegaSyrineMay
 
Bacterial Identification and Classifications
Bacterial Identification and ClassificationsBacterial Identification and Classifications
Bacterial Identification and ClassificationsAreesha Ahmad
 
Dubai Call Girls Beauty Face Teen O525547819 Call Girls Dubai Young
Dubai Call Girls Beauty Face Teen O525547819 Call Girls Dubai YoungDubai Call Girls Beauty Face Teen O525547819 Call Girls Dubai Young
Dubai Call Girls Beauty Face Teen O525547819 Call Girls Dubai Youngkajalvid75
 
Proteomics: types, protein profiling steps etc.
Proteomics: types, protein profiling steps etc.Proteomics: types, protein profiling steps etc.
Proteomics: types, protein profiling steps etc.Silpa
 
Vip profile Call Girls In Lonavala 9748763073 For Genuine Sex Service At Just...
Vip profile Call Girls In Lonavala 9748763073 For Genuine Sex Service At Just...Vip profile Call Girls In Lonavala 9748763073 For Genuine Sex Service At Just...
Vip profile Call Girls In Lonavala 9748763073 For Genuine Sex Service At Just...Monika Rani
 
Module for Grade 9 for Asynchronous/Distance learning
Module for Grade 9 for Asynchronous/Distance learningModule for Grade 9 for Asynchronous/Distance learning
Module for Grade 9 for Asynchronous/Distance learninglevieagacer
 
Pests of mustard_Identification_Management_Dr.UPR.pdf
Pests of mustard_Identification_Management_Dr.UPR.pdfPests of mustard_Identification_Management_Dr.UPR.pdf
Pests of mustard_Identification_Management_Dr.UPR.pdfPirithiRaju
 
SAMASTIPUR CALL GIRL 7857803690 LOW PRICE ESCORT SERVICE
SAMASTIPUR CALL GIRL 7857803690  LOW PRICE  ESCORT SERVICESAMASTIPUR CALL GIRL 7857803690  LOW PRICE  ESCORT SERVICE
SAMASTIPUR CALL GIRL 7857803690 LOW PRICE ESCORT SERVICEayushi9330
 
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.Nitya salvi
 
Thyroid Physiology_Dr.E. Muralinath_ Associate Professor
Thyroid Physiology_Dr.E. Muralinath_ Associate ProfessorThyroid Physiology_Dr.E. Muralinath_ Associate Professor
Thyroid Physiology_Dr.E. Muralinath_ Associate Professormuralinath2
 

Recently uploaded (20)

development of diagnostic enzyme assay to detect leuser virus
development of diagnostic enzyme assay to detect leuser virusdevelopment of diagnostic enzyme assay to detect leuser virus
development of diagnostic enzyme assay to detect leuser virus
 
GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)GBSN - Microbiology (Unit 1)
GBSN - Microbiology (Unit 1)
 
Human & Veterinary Respiratory Physilogy_DR.E.Muralinath_Associate Professor....
Human & Veterinary Respiratory Physilogy_DR.E.Muralinath_Associate Professor....Human & Veterinary Respiratory Physilogy_DR.E.Muralinath_Associate Professor....
Human & Veterinary Respiratory Physilogy_DR.E.Muralinath_Associate Professor....
 
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdfPests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
Pests of cotton_Borer_Pests_Binomics_Dr.UPR.pdf
 
Pests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdfPests of cotton_Sucking_Pests_Dr.UPR.pdf
Pests of cotton_Sucking_Pests_Dr.UPR.pdf
 
Introduction to Viruses
Introduction to VirusesIntroduction to Viruses
Introduction to Viruses
 
Locating and isolating a gene, FISH, GISH, Chromosome walking and jumping, te...
Locating and isolating a gene, FISH, GISH, Chromosome walking and jumping, te...Locating and isolating a gene, FISH, GISH, Chromosome walking and jumping, te...
Locating and isolating a gene, FISH, GISH, Chromosome walking and jumping, te...
 
Connaught Place, Delhi Call girls :8448380779 Model Escorts | 100% verified
Connaught Place, Delhi Call girls :8448380779 Model Escorts | 100% verifiedConnaught Place, Delhi Call girls :8448380779 Model Escorts | 100% verified
Connaught Place, Delhi Call girls :8448380779 Model Escorts | 100% verified
 
9999266834 Call Girls In Noida Sector 22 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 22 (Delhi) Call Girl Service9999266834 Call Girls In Noida Sector 22 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 22 (Delhi) Call Girl Service
 
Factory Acceptance Test( FAT).pptx .
Factory Acceptance Test( FAT).pptx       .Factory Acceptance Test( FAT).pptx       .
Factory Acceptance Test( FAT).pptx .
 
Grade 7 - Lesson 1 - Microscope and Its Functions
Grade 7 - Lesson 1 - Microscope and Its FunctionsGrade 7 - Lesson 1 - Microscope and Its Functions
Grade 7 - Lesson 1 - Microscope and Its Functions
 
Bacterial Identification and Classifications
Bacterial Identification and ClassificationsBacterial Identification and Classifications
Bacterial Identification and Classifications
 
Dubai Call Girls Beauty Face Teen O525547819 Call Girls Dubai Young
Dubai Call Girls Beauty Face Teen O525547819 Call Girls Dubai YoungDubai Call Girls Beauty Face Teen O525547819 Call Girls Dubai Young
Dubai Call Girls Beauty Face Teen O525547819 Call Girls Dubai Young
 
Proteomics: types, protein profiling steps etc.
Proteomics: types, protein profiling steps etc.Proteomics: types, protein profiling steps etc.
Proteomics: types, protein profiling steps etc.
 
Vip profile Call Girls In Lonavala 9748763073 For Genuine Sex Service At Just...
Vip profile Call Girls In Lonavala 9748763073 For Genuine Sex Service At Just...Vip profile Call Girls In Lonavala 9748763073 For Genuine Sex Service At Just...
Vip profile Call Girls In Lonavala 9748763073 For Genuine Sex Service At Just...
 
Module for Grade 9 for Asynchronous/Distance learning
Module for Grade 9 for Asynchronous/Distance learningModule for Grade 9 for Asynchronous/Distance learning
Module for Grade 9 for Asynchronous/Distance learning
 
Pests of mustard_Identification_Management_Dr.UPR.pdf
Pests of mustard_Identification_Management_Dr.UPR.pdfPests of mustard_Identification_Management_Dr.UPR.pdf
Pests of mustard_Identification_Management_Dr.UPR.pdf
 
SAMASTIPUR CALL GIRL 7857803690 LOW PRICE ESCORT SERVICE
SAMASTIPUR CALL GIRL 7857803690  LOW PRICE  ESCORT SERVICESAMASTIPUR CALL GIRL 7857803690  LOW PRICE  ESCORT SERVICE
SAMASTIPUR CALL GIRL 7857803690 LOW PRICE ESCORT SERVICE
 
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
❤Jammu Kashmir Call Girls 8617697112 Personal Whatsapp Number 💦✅.
 
Thyroid Physiology_Dr.E. Muralinath_ Associate Professor
Thyroid Physiology_Dr.E. Muralinath_ Associate ProfessorThyroid Physiology_Dr.E. Muralinath_ Associate Professor
Thyroid Physiology_Dr.E. Muralinath_ Associate Professor
 

Coin Change Problem

  • 1. Coin Change Problem   Finding the number of ways of making changes for a particular amount of cents, n, using a given set of denominations C={c1…cd} (e.g, the US coin system: {1, 5, 10, 25, 50, 100}) –  An example: n = 4,C = {1,2,3}, solutions: {1,1,1,1}, {1,1,2},{2,2},{1,3}.   Minimizing the number of coins returned for a particular quantity of change (available coins {1, 5, 10, 25}) –  30 Cents (solution: 25 + 2, two coins) –  67 Cents ?   17 cents given denominations = {1, 2, 3, 4}?
  • 3. Find the Fewest Coins: Casher’s algorithm   Given 30 cents, and coins {1, 5, 10, 25}   Here is what a casher will do: always go with coins of highest value first –  Choose the coin with highest value 25 •  1 quarter –  Now we have 5 cents left •  1 nickel The solution is: 2 (one quarter + one nickel)
  • 4. Greedy Algorithm Does not Always Give Optimal Solution to Coin Change Problem   Coins = {1, 3, 4, 5}   7 cents = ?   Coins = {1, 3, 4, 5}   7 cents = ?   Greedy solution: –  3 coins: one 5 + two 1   Optimal solution: –  2 coins: one 3 + one 4
  • 5. Find the Fewest Coins: Divide and Conquer   30 cents, given coins {1, 5, 10, 25, 50}, we need to calculate MinChange(30)   Choose the smallest of the following: –  1 + MinChange(29) #give a penny –  1 + MinChange(25) #give a nickel –  1 + MinChange(10) #give a dime –  1 + MinChange(5) #give a quarter   Do not know MinChange(29), MinChange(25), MinChange(10), MinChange(5)?
  • 6. Coin Change Problem: A Recursive Algorithm 1.  MinChange(M) 2.  if M = 0 3.  return 0 4.  v  ∞ 5.  for c in denominations ≤ M 6.  v  min {MinChange(M-c) + 1, v} 7.  return v
  • 7. Recursive Algorithm Is Not Efficient   It recalculates the optimal coin combination for a given amount of money repeatedly 30 29 25 5 2428 4 1 5 25 27 26 25 20
  • 8. How to avoid computing the same function multiple times   We’re re-computing values in our algorithm more than once   Save results of each computation for 0 to M   This way, we can do a reference call to find an already computed value, instead of re- computing each time   Running time M*d, where M is the value of money and d is the number of denominations
  • 9. Coin Change Problem: Save the Intermediate Results 1.  MinChange(M) 2.  if minChange[M] not empty 3.  return minChange[M] 4.  if M = 0 5.  return 0 6.  for c in denominations ≤ M 7.  v  min {MinChange(M-c) + 1, v} 8.  minChange[M] = v 9.  return v
  • 10. The Change Problem: Dynamic Programming 1.  MinChangeDP(M) 2.  minCoin[0]  0 3.  for m  1 to M 4.  minCoin[m] infinity 5.  for c in denominations ≤ M 6.  if minCoin[m-c] + 1 < minCoin[m] 7.  minCoin[m]minCoin[m-c] + 1 8.  return minCoin[M]
  • 11. Proof: Let N be the amount to be paid. Let the optimal solution be P=A*10 + B*5 + C. Clearly B≤1 (otherwise we can decrease B by 2 and increase A by 1, improving the solution). Similarly, C≤4. Let the solution given by GreedyCoinChange be P=a*10 + b*5 + c. Clearly b≤1 (otherwise the algorithm would output 10 instead of 5). Similarly c≤4. From 0≤ C≤4 and P=(2A+B)*5+C we have C=P mod 5. Similarly c=P mod 5, and hence c=C. Let Q=(P-C)/5. From 0≤ B≤ 1 and Q = 2A + B we have B=Q mod 2. Similarly b=Q mod 2, and hence b=B. Thus a=A, b=B, c=C, i.e., the solution given by GreedyCoinChange is optimal. Greedy algorithm outputs optimal solutions for coin values 10, 5, 1