
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Coin Change in Python
Suppose we have coins of different denominations and a total amount of money amount. We have to define one function to compute the fewest number of coins that we need to make up that amount. When that amount of money cannot be accommodated by any combination of the coins, return -1. So if the input is [1,2,5], and the amount is 11, the output is 3. This is formed using 5 + 5 + 1 = 11.
To solve this, we will follow these steps −
- if amount = 0, then return 0
- if minimum of coins array > amount, then return -1
- define one array called dp, of size amount + 1, and fill this with -1
- for i in range coins array
- if i > length of dp – 1, then skip the next part, go for the next iteration
- dp[i] := 1
- for j in range i + 1 to amount
- if dp[j – 1] = -1, then skip the next part, go for the next iteration
- otherwise if dp[j] = -1, then dp[j] := dp[j - i] + 1
- otherwise dp[j] := minimum of dp[j] and dp[j – i] + 1
- return dp[amount]
Example
Let us see the following implementation to get better understanding −
class Solution(object): def coinChange(self, coins, amount): if amount == 0 : return 0 if min(coins) > amount: return -1 dp = [-1 for i in range(0, amount + 1)] for i in coins: if i > len(dp) - 1: continue dp[i] = 1 for j in range(i + 1, amount + 1): if dp[j - i] == -1: continue elif dp[j] == -1: dp[j] = dp[j - i] + 1 else: dp[j] = min(dp[j], dp[j - i] + 1) #print(dp) return dp[amount] ob1 = Solution() print(ob1.coinChange([1,2,5], 11))
Input
[1,2,5] 11
Output
3
- Related Questions & Answers
- Python Program for Coin Change
- Minimum Coin Change Problem
- C Program Coin Change
- Coin Change 2 in C++
- How to implement coin change problem using topDown approach using C#?
- Coin Path in C++
- How to implement coin change problem using bottom-up approach using C#?
- Java Program to Toss a Coin
- Predict the winner in Coin Game in C++
- Lemonade Change in Python
- Program to find maximum amount of coin we can collect from a given matrix in Python
- Program to find number of distinct coin sums we can make with coins and quantities in Python?
- C++ Program to Generate a Random Subset by Coin Flipping
- How to change file permissions in Python?
- How to change file extension in Python?
Advertisements