![]() |
VOOZH | about |
There are n children and m apples that will be distributed to them. Your task is to count the number of ways this can be done.
Examples:
Input: n = 3, m = 2
Output: 6
Explanation: There are 6 ways to distribute 2 apples among 3 children: [0, 0, 2], [0, 1, 1], [0, 2, 0], [1, 0, 1], [1, 1, 0] and [2, 0, 0].Input: n = 4, m = 2
Output: 10
Explanation: There are 10 ways to distribute 2 apples among 4 children: [0, 0, 0, 2], [0, 0, 2, 0], [0, 2, 0, 0], [2, 0, 0, 0], [0, 0, 1, 1], [0, 1, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0], [1, 0, 1, 0] and [1, 1, 0, 0]
Approach: To solve the problem, follow the below idea:
To solve this problem, we can use the concept of the Combinatorics and Precomputation. The number of ways to the distribute m apples among n children is equivalent to finding the number of the combinations of the selecting nā1 separators from the total of the m+nā1 positions. This is because the apples and children can be represented as a sequence of the apples followed by the nā1 separators where each separator represents the boundary between the two consecutive children.
Step-by-step algorithm:
Below is the implementation of the algorithm:
10
Time Complexity: N*logN
Auxiliary Space: O(1)