Program to count number of ways we can distribute coins to workers in Python


Suppose we have two lists of positive numbers called coins and salaries. Here coins[i] indicates the value for coin i and salaries[j] indicates the least amount of salary required to pay for worker j. Now suppose we have one coin per type and we must give each worker exactly one coin, we have to compute the number of ways to give coins to each worker. Here two ways are different if some worker receives one type of coin in one way but a different type of coin in the other way. If the result is very large return result mod 10^9+7.

So, if the input is like coins = [1, 2, 3], salaries = [1, 2], then the output will be 4, as if we do not use the first coin (value 1), then both coins are valid for both workers, so there are two ways to pay the workers. Now if we use the first coin, then it can only go to the first worker, and then we can use any one of the remaining coin to pay the second worker. So there are four ways.

To solve this, we will follow these steps −

  • sort the list coins, and sort the list salaries
  • num_coins := size of coins
  • num_salaries := size of salaries
  • dp := a new map
  • for each salary in salaries, do
    • l := 0, r := num_coins - 1
    • idx := num_coins
    • while l <= r, do
      • m := l +(r - l) / 2
      • if coins[m] >= salary, then
        • idx := m
        • r := m - 1
      • otherwise,
        • l := m + 1
    • if idx is same as num_coins, then
      • return 0
    • dp[salary] := idx
  • res := 1
  • for i in range num_salaries - 1 to 0, decrease by 1, do
    • salary := salaries[i]
    • idx := dp[salary]
    • res := res *(num_coins - idx + 1) -(num_salaries - i)
  • return res mod 10^9+7

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, coins, salaries):
      coins.sort()
      salaries.sort()
      num_coins = len(coins)
      num_salaries = len(salaries)
      dp = {}
      for salary in salaries:
         l = 0
         r = num_coins - 1
         idx = num_coins
         while l <= r:
            m = l + (r - l) // 2
            if coins[m] >= salary:
               idx = m
               r = m - 1
            else:
               l = m + 1
         if idx == num_coins:
            return 0
         dp[salary] = idx
      res = 1
      for i in range(num_salaries - 1, -1, -1):
         salary = salaries[i]
         idx = dp[salary]
         res *= (num_coins - idx + 1) - (num_salaries - i)
      return res % (10**9+7)
ob = Solution()
coins = [1, 2, 3]
salaries = [1, 2]
print(ob.solve(coins, salaries))

Input

[1, 2, 3],[1, 2]

Output

4

Updated on: 20-Oct-2020

237 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements