Distribute Candies Among Children III - Problem
You're a parent with n candies to distribute fairly among your 3 children. Each child has a sweet tooth, but you want to ensure no child gets more than limit candies to avoid a sugar rush!
Your task is to find the total number of ways to distribute all n candies among the 3 children such that:
- Every candy must be given to some child (no leftovers)
- No child receives more than
limitcandies - A child can receive 0 candies (they might be satisfied already)
Example: With n = 5 candies and limit = 2, one valid distribution is (2, 2, 1) - first child gets 2, second gets 2, third gets 1.
Input & Output
example_1.py β Basic Case
$
Input:
n = 5, limit = 2
βΊ
Output:
3
π‘ Note:
Valid distributions are: (0,2,3) - invalid since 3>2, (1,2,2), (2,1,2), (2,2,1). After checking all combinations systematically: (0,1,4) invalid, (0,2,3) invalid, (1,0,4) invalid, (1,1,3) invalid, (1,2,2) valid, (2,0,3) invalid, (2,1,2) valid, (2,2,1) valid. Total: 3 ways.
example_2.py β Small Numbers
$
Input:
n = 3, limit = 3
βΊ
Output:
10
π‘ Note:
With no effective limit constraint (since max any child can get is 3), this becomes a standard stars and bars problem. All possible distributions: (0,0,3), (0,1,2), (0,2,1), (0,3,0), (1,0,2), (1,1,1), (1,2,0), (2,0,1), (2,1,0), (3,0,0). Total: 10 ways.
example_3.py β Edge Case
$
Input:
n = 1, limit = 1
βΊ
Output:
3
π‘ Note:
With only 1 candy and limit 1, each child can receive either 0 or 1 candy. Valid distributions: (1,0,0), (0,1,0), (0,0,1). Each child gets exactly 1 candy in one of the distributions. Total: 3 ways.
Constraints
- 1 β€ n β€ 106
- 1 β€ limit β€ 106
- Each child can receive 0 to limit candies
- All n candies must be distributed
Visualization
Tap to expand
Understanding the Visualization
1
Stars and Bars Setup
Imagine n stars (candies) and 2 bars to create 3 groups (children)
2
Count Total Ways
Without restrictions: C(n+2, 2) total arrangements
3
Apply Constraints
Use inclusion-exclusion to remove invalid distributions
4
Final Count
Result gives valid ways respecting the limit constraint
Key Takeaway
π― Key Insight: The inclusion-exclusion principle elegantly handles constrained counting problems by systematically removing invalid cases from the total count.
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code