VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-distributing-apples/

⇱ CSES Solutions – Distributing Apples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions – Distributing Apples

Last Updated : 23 Jul, 2025

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:

  • Calculate the total number of the positions (apples + separators).
  • Initialize the result as 1.
  • Calculate the number of the combinations using the formula.
  • Iterate from 1 to n-1 and update the result accordingly.
  • Return the final result as the number of ways to the distribute the apples among the children.

Below is the implementation of the algorithm:


Output
10

Time Complexity: N*logN
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: