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 limit candies
  • 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
Stars and Bars VisualizationExample: n=5 candies, limit=25 candies (stars)2 dividers (bars)Child 1≀ 2 candiesChild 2≀ 2 candiesChild 3≀ 2 candiesMathematical FormulaTotal unrestricted = C(n+2, 2)Subtract: 3 Γ— C(n-limit-1+2, 2)Add back: 3 Γ— C(n-2(limit+1)+2, 2)Subtract: C(n-3(limit+1)+2, 2)Result: 3 valid ways to distribute(1,2,2)(2,1,2)(2,2,1)
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.
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28
21.1K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
πŸ’‘ Explanation
AI Ready
πŸ’‘ Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen