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 versus NP
P versus NPP versus NP
P versus NP
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programing
 
5.2 divide and conquer
5.2 divide and conquer5.2 divide and conquer
5.2 divide and conquer
 
Backtracking
Backtracking  Backtracking
Backtracking
 
NP completeness
NP completenessNP completeness
NP completeness
 
Minimum spanning tree
Minimum spanning treeMinimum spanning tree
Minimum spanning tree
 
Longest Common Subsequence
Longest Common SubsequenceLongest Common Subsequence
Longest Common Subsequence
 
Greedy algorithm
Greedy algorithmGreedy algorithm
Greedy algorithm
 
Greedy method
Greedy methodGreedy method
Greedy method
 
NP Complete Problems
NP Complete ProblemsNP Complete Problems
NP Complete Problems
 
Tsp branch and bound
Tsp branch and boundTsp branch and bound
Tsp branch and bound
 
Bellman ford algorithm
Bellman ford algorithmBellman ford algorithm
Bellman ford algorithm
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
Greedy Algorithm
Greedy AlgorithmGreedy Algorithm
Greedy Algorithm
 
Shortest path algorithms
Shortest path algorithmsShortest path algorithms
Shortest path algorithms
 
Job sequencing with deadline
Job sequencing with deadlineJob sequencing with deadline
Job sequencing with deadline
 
9. chapter 8 np hard and np complete problems
9. chapter 8   np hard and np complete problems9. chapter 8   np hard and np complete problems
9. chapter 8 np hard and np complete problems
 
Single source stortest path bellman ford and dijkstra
Single source stortest path bellman ford and dijkstraSingle source stortest path bellman ford and dijkstra
Single source stortest path bellman ford and dijkstra
 
Lecture 4 asymptotic notations
Lecture 4   asymptotic notationsLecture 4   asymptotic notations
Lecture 4 asymptotic notations
 

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

Disentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOSTDisentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOSTSérgio Sacani
 
Biopesticide (2).pptx .This slides helps to know the different types of biop...
Biopesticide (2).pptx  .This slides helps to know the different types of biop...Biopesticide (2).pptx  .This slides helps to know the different types of biop...
Biopesticide (2).pptx .This slides helps to know the different types of biop...RohitNehra6
 
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...Sérgio Sacani
 
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Nistarini College, Purulia (W.B) India
 
Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )aarthirajkumar25
 
Hubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroidsHubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroidsSérgio Sacani
 
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfBehavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfSELF-EXPLANATORY
 
Grafana in space: Monitoring Japan's SLIM moon lander in real time
Grafana in space: Monitoring Japan's SLIM moon lander  in real timeGrafana in space: Monitoring Japan's SLIM moon lander  in real time
Grafana in space: Monitoring Japan's SLIM moon lander in real timeSatoshi NAKAHIRA
 
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bNightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bSérgio Sacani
 
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...anilsa9823
 
Luciferase in rDNA technology (biotechnology).pptx
Luciferase in rDNA technology (biotechnology).pptxLuciferase in rDNA technology (biotechnology).pptx
Luciferase in rDNA technology (biotechnology).pptxAleenaTreesaSaji
 
NAVSEA PEO USC - Unmanned & Small Combatants 26Oct23.pdf
NAVSEA PEO USC - Unmanned & Small Combatants 26Oct23.pdfNAVSEA PEO USC - Unmanned & Small Combatants 26Oct23.pdf
NAVSEA PEO USC - Unmanned & Small Combatants 26Oct23.pdfWadeK3
 
Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)PraveenaKalaiselvan1
 
Analytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdfAnalytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdfSwapnil Therkar
 
Scheme-of-Work-Science-Stage-4 cambridge science.docx
Scheme-of-Work-Science-Stage-4 cambridge science.docxScheme-of-Work-Science-Stage-4 cambridge science.docx
Scheme-of-Work-Science-Stage-4 cambridge science.docxyaramohamed343013
 
Animal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxAnimal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxUmerFayaz5
 
G9 Science Q4- Week 1-2 Projectile Motion.ppt
G9 Science Q4- Week 1-2 Projectile Motion.pptG9 Science Q4- Week 1-2 Projectile Motion.ppt
G9 Science Q4- Week 1-2 Projectile Motion.pptMAESTRELLAMesa2
 
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptxSOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptxkessiyaTpeter
 

Recently uploaded (20)

Disentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOSTDisentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOST
 
Biopesticide (2).pptx .This slides helps to know the different types of biop...
Biopesticide (2).pptx  .This slides helps to know the different types of biop...Biopesticide (2).pptx  .This slides helps to know the different types of biop...
Biopesticide (2).pptx .This slides helps to know the different types of biop...
 
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
 
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
 
Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...
 
Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )
 
Hubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroidsHubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroids
 
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfBehavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
 
Grafana in space: Monitoring Japan's SLIM moon lander in real time
Grafana in space: Monitoring Japan's SLIM moon lander  in real timeGrafana in space: Monitoring Japan's SLIM moon lander  in real time
Grafana in space: Monitoring Japan's SLIM moon lander in real time
 
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bNightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
 
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
 
Luciferase in rDNA technology (biotechnology).pptx
Luciferase in rDNA technology (biotechnology).pptxLuciferase in rDNA technology (biotechnology).pptx
Luciferase in rDNA technology (biotechnology).pptx
 
NAVSEA PEO USC - Unmanned & Small Combatants 26Oct23.pdf
NAVSEA PEO USC - Unmanned & Small Combatants 26Oct23.pdfNAVSEA PEO USC - Unmanned & Small Combatants 26Oct23.pdf
NAVSEA PEO USC - Unmanned & Small Combatants 26Oct23.pdf
 
9953056974 Young Call Girls In Mahavir enclave Indian Quality Escort service
9953056974 Young Call Girls In Mahavir enclave Indian Quality Escort service9953056974 Young Call Girls In Mahavir enclave Indian Quality Escort service
9953056974 Young Call Girls In Mahavir enclave Indian Quality Escort service
 
Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)Recombinant DNA technology (Immunological screening)
Recombinant DNA technology (Immunological screening)
 
Analytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdfAnalytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdf
 
Scheme-of-Work-Science-Stage-4 cambridge science.docx
Scheme-of-Work-Science-Stage-4 cambridge science.docxScheme-of-Work-Science-Stage-4 cambridge science.docx
Scheme-of-Work-Science-Stage-4 cambridge science.docx
 
Animal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxAnimal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptx
 
G9 Science Q4- Week 1-2 Projectile Motion.ppt
G9 Science Q4- Week 1-2 Projectile Motion.pptG9 Science Q4- Week 1-2 Projectile Motion.ppt
G9 Science Q4- Week 1-2 Projectile Motion.ppt
 
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptxSOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
 

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