Distribute Candies Among Children I - Problem

You are given two positive integers n and limit.

Return the total number of ways to distribute n candies among 3 children such that no child gets more than limit candies.

Each child can receive 0 or more candies, and the sum of all candies distributed must equal n.

Input & Output

Example 1 — Basic Case
$ Input: n = 5, limit = 2
Output: 3
💡 Note: Valid distributions: (0,2,3) is invalid since 3>2, but (1,2,2), (2,1,2), (2,2,1) are valid. Actually there are 3 valid ways total.
Example 2 — Small Values
$ Input: n = 3, limit = 3
Output: 10
💡 Note: With high limit, all combinations work: (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)
Example 3 — Tight Constraint
$ Input: n = 4, limit = 1
Output: 0
💡 Note: Impossible: need to distribute 4 candies but each child can only get max 1, so 3×1 = 3 < 4

Constraints

  • 1 ≤ n ≤ 50
  • 1 ≤ limit ≤ 50

Visualization

Tap to expand
Distribute 5 candies among 3 children (max 2 each)🍬🍬🍬🍬🍬5 candies to distributeChild 1Child 2Child 3Max: 2 candiesMax: 2 candiesMax: 2 candiesFind all valid distributions: (a,b,c) where a+b+c=5 and a,b,c ≤ 2Answer: Count of valid combinations
Understanding the Visualization
1
Input
n=5 candies, limit=2 per child
2
Constraint
Each child gets 0 to limit candies, sum = n
3
Count
Find all valid (child1, child2, child3) combinations
Key Takeaway
🎯 Key Insight: This is a constrained stars-and-bars combinatorial problem that can be solved efficiently using mathematical formulas
Asked in
Google 15 Microsoft 12 Amazon 8
23.4K Views
Medium Frequency
~15 min Avg. Time
890 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