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

Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1Amrinder Arora
 
Sum of subsets problem by backtracking 
Sum of subsets problem by backtracking Sum of subsets problem by backtracking 
Sum of subsets problem by backtracking Hasanain Alshadoodee
 
Bellman-Ford-Moore Algorithm and Dijkstra’s Algorithm
Bellman-Ford-Moore Algorithm and Dijkstra’s AlgorithmBellman-Ford-Moore Algorithm and Dijkstra’s Algorithm
Bellman-Ford-Moore Algorithm and Dijkstra’s AlgorithmFulvio Corno
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithmsGanesh Solanke
 
Bellman Ford Routing Algorithm-Computer Networks
Bellman Ford Routing Algorithm-Computer NetworksBellman Ford Routing Algorithm-Computer Networks
Bellman Ford Routing Algorithm-Computer NetworksSimranJain63
 
5.2 divide and conquer
5.2 divide and conquer5.2 divide and conquer
5.2 divide and conquerKrish_ver2
 
Presentation of daa on approximation algorithm and vertex cover problem
Presentation of daa on approximation algorithm and vertex cover problem Presentation of daa on approximation algorithm and vertex cover problem
Presentation of daa on approximation algorithm and vertex cover problem sumit gyawali
 
BackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesBackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesFahim Ferdous
 
Max flow min cut
Max flow min cutMax flow min cut
Max flow min cutMayank Garg
 
Little o and little omega
Little o and little omegaLittle o and little omega
Little o and little omegaRajesh K Shukla
 
Divide and conquer 1
Divide and conquer 1Divide and conquer 1
Divide and conquer 1Kumar
 

What's hot (20)

Tsp branch and-bound
Tsp branch and-boundTsp branch and-bound
Tsp branch and-bound
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1
 
Prim's algorithm
Prim's algorithmPrim's algorithm
Prim's algorithm
 
Branch and bound
Branch and boundBranch and bound
Branch and bound
 
Bellman ford algorithm
Bellman ford algorithmBellman ford algorithm
Bellman ford algorithm
 
Sum of subsets problem by backtracking 
Sum of subsets problem by backtracking Sum of subsets problem by backtracking 
Sum of subsets problem by backtracking 
 
Bellman-Ford-Moore Algorithm and Dijkstra’s Algorithm
Bellman-Ford-Moore Algorithm and Dijkstra’s AlgorithmBellman-Ford-Moore Algorithm and Dijkstra’s Algorithm
Bellman-Ford-Moore Algorithm and Dijkstra’s Algorithm
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
 
Bellman Ford Routing Algorithm-Computer Networks
Bellman Ford Routing Algorithm-Computer NetworksBellman Ford Routing Algorithm-Computer Networks
Bellman Ford Routing Algorithm-Computer Networks
 
A petri-net
A petri-netA petri-net
A petri-net
 
graph theory
graph theory graph theory
graph theory
 
5.2 divide and conquer
5.2 divide and conquer5.2 divide and conquer
5.2 divide and conquer
 
Presentation of daa on approximation algorithm and vertex cover problem
Presentation of daa on approximation algorithm and vertex cover problem Presentation of daa on approximation algorithm and vertex cover problem
Presentation of daa on approximation algorithm and vertex cover problem
 
Approximation Algorithms
Approximation AlgorithmsApproximation Algorithms
Approximation Algorithms
 
BackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesBackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and Examples
 
Max flow min cut
Max flow min cutMax flow min cut
Max flow min cut
 
Backtracking
BacktrackingBacktracking
Backtracking
 
Little o and little omega
Little o and little omegaLittle o and little omega
Little o and little omega
 
Divide and conquer 1
Divide and conquer 1Divide and conquer 1
Divide and conquer 1
 
Graph algorithm
Graph algorithmGraph algorithm
Graph algorithm
 

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

preservation, maintanence and improvement of industrial organism.pptx
preservation, maintanence and improvement of industrial organism.pptxpreservation, maintanence and improvement of industrial organism.pptx
preservation, maintanence and improvement of industrial organism.pptxnoordubaliya2003
 
Neurodevelopmental disorders according to the dsm 5 tr
Neurodevelopmental disorders according to the dsm 5 trNeurodevelopmental disorders according to the dsm 5 tr
Neurodevelopmental disorders according to the dsm 5 trssuser06f238
 
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptxTHE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptxNandakishor Bhaurao Deshmukh
 
Pests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdfPests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdfPirithiRaju
 
FREE NURSING BUNDLE FOR NURSES.PDF by na
FREE NURSING BUNDLE FOR NURSES.PDF by naFREE NURSING BUNDLE FOR NURSES.PDF by na
FREE NURSING BUNDLE FOR NURSES.PDF by naJASISJULIANOELYNV
 
Microphone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptxMicrophone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptxpriyankatabhane
 
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
 
Speech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptxSpeech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptxpriyankatabhane
 
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.aasikanpl
 
User Guide: Orion™ Weather Station (Columbia Weather Systems)
User Guide: Orion™ Weather Station (Columbia Weather Systems)User Guide: Orion™ Weather Station (Columbia Weather Systems)
User Guide: Orion™ Weather Station (Columbia Weather Systems)Columbia Weather Systems
 
User Guide: Capricorn FLX™ Weather Station
User Guide: Capricorn FLX™ Weather StationUser Guide: Capricorn FLX™ Weather Station
User Guide: Capricorn FLX™ Weather StationColumbia Weather Systems
 
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
 
GenBio2 - Lesson 1 - Introduction to Genetics.pptx
GenBio2 - Lesson 1 - Introduction to Genetics.pptxGenBio2 - Lesson 1 - Introduction to Genetics.pptx
GenBio2 - Lesson 1 - Introduction to Genetics.pptxBerniceCayabyab1
 
Topic 9- General Principles of International Law.pptx
Topic 9- General Principles of International Law.pptxTopic 9- General Principles of International Law.pptx
Topic 9- General Principles of International Law.pptxJorenAcuavera1
 
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
 
Solution chemistry, Moral and Normal solutions
Solution chemistry, Moral and Normal solutionsSolution chemistry, Moral and Normal solutions
Solution chemistry, Moral and Normal solutionsHajira Mahmood
 
User Guide: Pulsar™ Weather Station (Columbia Weather Systems)
User Guide: Pulsar™ Weather Station (Columbia Weather Systems)User Guide: Pulsar™ Weather Station (Columbia Weather Systems)
User Guide: Pulsar™ Weather Station (Columbia Weather Systems)Columbia Weather Systems
 
Base editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editingBase editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editingNetHelix
 

Recently uploaded (20)

preservation, maintanence and improvement of industrial organism.pptx
preservation, maintanence and improvement of industrial organism.pptxpreservation, maintanence and improvement of industrial organism.pptx
preservation, maintanence and improvement of industrial organism.pptx
 
Neurodevelopmental disorders according to the dsm 5 tr
Neurodevelopmental disorders according to the dsm 5 trNeurodevelopmental disorders according to the dsm 5 tr
Neurodevelopmental disorders according to the dsm 5 tr
 
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptxTHE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
 
Pests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdfPests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdf
 
FREE NURSING BUNDLE FOR NURSES.PDF by na
FREE NURSING BUNDLE FOR NURSES.PDF by naFREE NURSING BUNDLE FOR NURSES.PDF by na
FREE NURSING BUNDLE FOR NURSES.PDF by na
 
Microphone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptxMicrophone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptx
 
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
 
Volatile Oils Pharmacognosy And Phytochemistry -I
Volatile Oils Pharmacognosy And Phytochemistry -IVolatile Oils Pharmacognosy And Phytochemistry -I
Volatile Oils Pharmacognosy And Phytochemistry -I
 
Speech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptxSpeech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptx
 
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
 
User Guide: Orion™ Weather Station (Columbia Weather Systems)
User Guide: Orion™ Weather Station (Columbia Weather Systems)User Guide: Orion™ Weather Station (Columbia Weather Systems)
User Guide: Orion™ Weather Station (Columbia Weather Systems)
 
User Guide: Capricorn FLX™ Weather Station
User Guide: Capricorn FLX™ Weather StationUser Guide: Capricorn FLX™ Weather Station
User Guide: Capricorn FLX™ Weather Station
 
Hot Sexy call girls in Moti Nagar,🔝 9953056974 🔝 escort Service
Hot Sexy call girls in  Moti Nagar,🔝 9953056974 🔝 escort ServiceHot Sexy call girls in  Moti Nagar,🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Moti Nagar,🔝 9953056974 🔝 escort Service
 
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
 
GenBio2 - Lesson 1 - Introduction to Genetics.pptx
GenBio2 - Lesson 1 - Introduction to Genetics.pptxGenBio2 - Lesson 1 - Introduction to Genetics.pptx
GenBio2 - Lesson 1 - Introduction to Genetics.pptx
 
Topic 9- General Principles of International Law.pptx
Topic 9- General Principles of International Law.pptxTopic 9- General Principles of International Law.pptx
Topic 9- General Principles of International Law.pptx
 
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 ...
 
Solution chemistry, Moral and Normal solutions
Solution chemistry, Moral and Normal solutionsSolution chemistry, Moral and Normal solutions
Solution chemistry, Moral and Normal solutions
 
User Guide: Pulsar™ Weather Station (Columbia Weather Systems)
User Guide: Pulsar™ Weather Station (Columbia Weather Systems)User Guide: Pulsar™ Weather Station (Columbia Weather Systems)
User Guide: Pulsar™ Weather Station (Columbia Weather Systems)
 
Base editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editingBase editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editing
 

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