Count ways of selecting X red balls and Y blue balls
Given integers A, B, C, and D, There are two boxes First Box has A red balls and B blue balls and the second box has C red balls and D blue balls, the task is to count ways to select 3 red balls and 3 blue balls so that there are 3 balls drawn from the first box and 3 balls drawn from the second box. (Print the answer modulo 109 + 7).
Input: A = 4, B =3, C = 3, D = 4
Input: A = 3, B = 3, C = 3, D = 3
Naive approach: The basic way to solve the problem is as follows:
The basic way to solve this problem is to generate all possible combinations by using a recursive approach.
Time Complexity: O(N!)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the following idea:
The problem can be solved with combinatorics:
Case 1: 2 red balls and 1 blue ball from box 1 and 1 red ball and 2 blue balls from box 2.
- Total ways of case1 = AC2 * BC1 * CC1 * DC2
Case 2: 3 red balls from box 1 and 3 blue balls from box 2.
- Total ways of case2 = AC3 * DC3
Case 3: 3 blue balls from box1 and 3 red balls from box 2
- Total ways of case3 = BC3 * CC3
Case 4: 1 red ball and 2 blue balls from box 1 and 2 red balls and 1 blue ball from box 2.
- Total ways of case4 = AC1 * BC2 * CC2 * DC1
Total ways = Total ways of case1 + Total ways of case2 + Total ways of case3 + Total ways of case 3 + Total ways of case4
instead of dividing factorials we multiply their modular multiplicative inverses.
Follow the steps below to solve the problem:
- Initializing fact array and Precomputing all factorials from 1 to 100000.
- initializing ANS variable.
- Calculating the answer by using the above formula.
- Print the answer.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
Please Login to comment...