VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-the-number-of-currency-notes-needed/

⇱ Count the number of currency notes needed - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count the number of currency notes needed

Last Updated : 9 Jun, 2022

You have an unlimited amount of banknotes worth A and B dollars (A not equals to B). You want to pay a total of S dollars using exactly N notes. The task is to find the number of notes worth A dollars you need. If there is no solution return -1.

Examples: 

Input: A = 1, B = 2, S = 7, N = 5 
Output:
3 * A + 2 * B = S 
3 * 1 + 2 * 2 = 7

Input: A = 2, B = 1, S = 7, N = 5 
Output: 2

Input: A = 2, B = 1, S = 4, N = 5 
Output: -1

Input: A = 2, B = 3, S = 20, N = 8 
Output:

Approach: Let x be the number of notes of value A required then the rest of the notes i.e. N - x must of value B. Since, their sum is required be S then the following equation must be satisfied:  

S = (A * x) + (B * (N - x)) 
Solving the equation further, 
S = (A * x) + (B * N) - (B * x) 
S - (B * N) = (A - B) * x 
x = (S - (B * N)) / (A - B) 
After solving for x, it is the number of notes of value A required 
only if the value of x is an integer else the result is not possible. 
 

Below is the implementation of the above approach: 


Output: 
3

 

Time Complexity: O(1)
Auxiliary Space: O(1)

Comment
Article Tags: