Given unlimited number of coins of two denomination X and Y. Also given bags with capacity of N rupees, independent of number of coins. The task is to find the minimum number of bags such that each bag contains the same amount of rupees and sum of all the bags amount is at least M.
Input : M = 27, N = 12, X = 2, Y = 5. Output : 3 We put 2 coins of X, 1 coin of Y in each bag. So we have 9 rupees in each bag and we need at least 3 bags (Note that 27/9 = 3). There is no way to obtain sum with lesser number of bags. Input : M = 45, N = 9, X = 4, Y = 5. Output : 5
The task is to minimize the number of bags, thus need to maximize the amount in a bag such that amount in all bags is same. Suppose we take, ‘p’ number of X coins and ‘q’ number of Y coins, then the task is to maximize p*X + q*Y. And also, p*X + q*Y <= N.
Now, to find the maximum possible value of Left Hand Side of the equation, vary p from 0 to N/X, then find the maximum possible q for the particular p. Then, out of all such pairs, take the (p, q) pair which gives maximum value of p*X + q*Y.
Below is the implementation of above idea :
Time Complexity : O(N/X)
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Count number of ways to divide a number in 4 parts
- Fifth root of a number
- Number of ways to calculate a target number using only array elements
- Happy Number
- Number of flips to make binary string alternate | Set 1
- Convert a number into negative base representation
- Minimum number of page turns to get to a desired page
- Maximum number of groups of size 3 containing two type of items
- Make n using 1s and 2s with minimum number of terms multiple of k
- Count of Numbers in Range where the number does not contain more than K non zero digits
- Find the largest composite number that divides N but is strictly lesser than N
- Maths behind number of paths in matrix problem
- Sum of minimum difference between consecutive elements of an array
- Minimum steps to reach target by a Knight | Set 2
- Number of subsequences with negative product