![]() |
VOOZH | about |
You are given a list of N coins of different denominations. You can pay an amount equivalent to any 1 coin and can acquire that coin. In addition, once you have paid for a coin, we can choose at most K more coins and can acquire those for free. The task is to find the minimum amount required to acquire all the N coins for a given value of K.
Examples :
Input : coin[] = {100, 20, 50, 10, 2, 5},
k = 3
Output : 7
Input : coin[] = {1, 2, 5, 10, 20, 50},
k = 3
Output : 3
As per the question, we can see that at a cost of 1 coin, we can acquire at most K+1 coins. Therefore, in order to acquire all the n coins, we will be choosing ceil(n/(k+1)) coins and the cost of choosing coins will be minimum if we choose the smallest ceil(n/(k+1)) ( Greedy approach). The smallest ceil(n/(k+1)) coins can be found by simply sorting all the N values in increasing order.
If we should check for time complexity (n log n) is for sorting element and (k) is for adding the total amount. So, finally Time Complexity: O(n log n).
Output :
3
Time Complexity: O(n log n)
Auxiliary Space: O(1)
Note that there are more efficient approaches to find the given number of smallest values. For example, method 6 of m largest(or smallest) elements in an array can find m'th smallest element in (n-m) Log m + m Log m).
How to handle multiple queries for a single predefined array?
In this case, if you are asked to find the above answer for many values of K, you have to compute it fast and our time complexity got increased as per the number of queries for k. For the purpose to serve, we can maintain a prefix sum array after sorting all the N values and can answer queries easily and quickly.
Suppose
Output :
3 1
Time Complexity: O(n log n)
Auxiliary Space: O(1)
After preprocessing, every query for a k takes O(1) time.