You are given N banknotes
} given by a customer to buy sweets. One sweet costs X units.
For the number of sweets the customer wants to buy, all the banknotes are supposed to be used, that is, you shouldn’t be able to buy that many sweets by discarding any banknote.
What is the largest number of sweets does the customer want to buy?
Check whether the smallest value can be ignored. If it can, the answer is -1. Otherwise, the answer is the maximum number of sweets the customer can buy.
S = ∑
(i = 1 to N)
Obviously, the customer can buy, at max
V = floor(S / X) sweets.
- It should be clear from the problem statement that you will always give the customer
- Since, the statement asks you to return the maximum number of sweets he can buy by using all the banknotes.
- All that remains to check is, whether you must use all the banknotes to buy
Vsweets or not.
- I.E. you need to check if V sweets can be bought by ignoring at least one of the banknotes, which results in the customer being “Inadequate”.
- If the customer is inadequate, you must print -1.
- Otherwise, the answer will be V.
V sweets, you must use at least
V * X amount of money.
R = S - (V * X) = S % X, where
% is the remainder (or modulo) operation.
If there is no banknote given whose value is less than
R, then the customer is adequate.
Also, if there is a banknote whose value is less than
R, then the customer is inadequate.
Let us say you could ignore a banknote
floor((S - b) / X) = V
floor((S - b) / X) = (S - R) / X
((S - b) / X) - (((S - b) % X) / X) = (S - R) / X
R - b = (S - b) % X
b > R then the above expression is absurd; since
R - b is negative and
(S - b) % X is positive.
b <= R then above expression is always true.
Thus, the necessary and sufficient condition for the customer to be adequate is that there is no banknote whose value is less tan or equal to S % X. The code to solve the problem will look like
M = minimum(x: x = A[i], for all i = 1 to N) S = sum(x: x = A[i], for all i = 1 to N) R = S % X if R < M print S / X else print -1
Can be found here
Can be found here