You have a collection of coins, and you know the values of the coins
and the quantity
of each type of coin in it. You want to know how many distinct sums you can make from non-empty groupings of these coins.
Example
For coins = [10, 50, 100]
and quantity = [1, 2, 1]
, the output should besolution(coins, quantity) = 9
.
Here are all the possible sums:
50 = 50
;10 + 50 = 60
;50 + 100 = 150
;10 + 50 + 100 = 160
;50 + 50 = 100
;10 + 50 + 50 = 110
;50 + 50 + 100 = 200
;10 + 50 + 50 + 100 = 210
;10 = 10
;100 = 100
;10 + 100 = 110
.
int solution(int[] coins, int[] quantity) {
// Create a HashSet to store all the possible sums
HashSet<Integer> sums = new HashSet<Integer>();
// Add 0 as a possible sum, as we can always make a sum of 0
sums.add(0);
// Loop through all the coins
for(int i=0; i<coins.length; i++) {
// Get the value of the current coin
int coin = coins[i];
// Create a new HashSet to store the current set of sums
HashSet<Integer> currentSums = new HashSet<Integer>();
// Loop through all the previous possible sums
for(Integer sum : sums) {
// Loop through the quantity of the current coin
for(int j=1; j<=quantity[i]; j++) {
// Add a new sum to the current set of sums
// by adding the current coin multiplied by the quantity
currentSums.add(sum + coin*j);
}
}
// Add all the new sums to the main set of sums
sums.addAll(currentSums);
}
// Return the size of the set of sums, minus 1 (to exclude the 0 sum we added earlier)
return sums.size() - 1;
}
Time complexity - O(m*n*sum.size())