Count the number of ways to distribute exactly n candies among 3 children with per-child upper bounds.
Problem
You are given an integer n representing the total number of candies, and three non-negative integers limit1, limit2, and limit3 representing the maximum candies each of the 3 children can receive.
Count how many different ways you can distribute all n candies among the children such that:
- each child receives a non-negative integer number of candies,
- the total number of candies distributed is exactly
n, - child
ireceives at mostlimiticandies.
Two distributions are different if at least one child receives a different number of candies.
Notes
- The children are distinct.
- Candy counts are integers.
- You must use all candies.
Input Format
- A single line or structured input containing three limits and the total number of candies.
- Conceptually:
n,limit1,limit2,limit3.
Output Format
- Return the number of valid distributions as an integer.
Constraints
0 <= n0 <= limit1, limit2, limit3- The answer fits in a standard integer type for the platform version of the problem.
Example 1
Input
n = 5, limit1 = 2, limit2 = 2, limit3 = 2
Output
3
Explanation
The valid distributions are (1,2,2), (2,1,2), and (2,2,1).
Example 2
Input
n = 3, limit1 = 1, limit2 = 1, limit3 = 1
Output
1
Explanation
Only (1,1,1) uses all 3 candies without exceeding any limit.
Show 1 more example
Example 3
Input
n = 4, limit1 = 0, limit2 = 2, limit3 = 3
Output
1
Explanation
Child 1 must receive 0, and the remaining 4 candies must be split as (1,3) between the other two children, which is the only valid distribution.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.