Program to find number of distinct coin sums we can make with coins and quantities in Python?



Suppose we have a list of values called coins and another list called quantities of the same length. The value of ith coin is coins[i] and we currently have quantities[i] number of ith coin. We have to find number of distinct coin sum values we can get by using non-empty group of these coins.

So, if the input is like coins = [1, 2, 5] quantities = [1, 2, 1], then the output will be 10, as we can have the following distinct coin sums [1] = 1, [2] = 2, [1,2] = 3, [2,2] = 4, [5] = 5,[1,5] = 6, [2,5] = 7, [1,2,5] = 8, [2,2,5] = 9, [1,2,2,5] = 10.

To solve this, we will follow these steps:

Define a function rec() . This will take i, res

if i is same as size of coins , then    return for k in range 0 to quantities[i] + 1, do    cur := res + k * coins[i]    insert cur into fres    rec(i + 1, cur) From the main method, do the following: fres := a new set rec(0, 0) return size of fres - 1

Example

 Live Demo

class Solution:    def solve(self, coins, quantities):       def rec(i, res):          if i == len(coins):             return          for k in range(0, quantities[i] + 1):             cur = res + k * coins[i]             fres.add(cur)             rec(i + 1, cur)       fres = set()       rec(0, 0)       return len(fres) - 1 ob = Solution() coins = [1, 2, 5] quantities = [1, 2, 1] print(ob.solve(coins, quantities))

Input

[1, 2, 5], [1, 2, 1]

Output

10
Updated on: 2020-11-10T09:12:25+05:30

614 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements