Distribute Candies Among Children III - 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: 6
💡 Note: Valid distributions: (0,1,4)✗, (0,2,3)✗, (1,1,3)✗, (1,2,2)✓, (2,1,2)✓, (2,2,1)✓, (0,0,5)✗, (1,0,4)✗, (2,0,3)✗, (0,1,4)✗, (0,2,3)✗. After checking all: (0,2,2)✓, (1,1,2)✓, (1,2,1)✓, (2,0,2)✓, (2,1,1)✓, (2,2,1)✓. Total = 6 valid ways.
Example 2 — Small Input
$ Input: n = 3, limit = 3
Output: 10
💡 Note: Since limit ≥ n, no child can exceed limit. All distributions are valid: (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 — Edge Case
$ Input: n = 1, limit = 1
Output: 3
💡 Note: Only 3 ways to give 1 candy to exactly one child: (1,0,0), (0,1,0), (0,0,1). Each satisfies the limit constraint.

Constraints

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

Visualization

Tap to expand
Distribute 5 Candies Among 3 Children (limit = 2)INPUTn = 5 candieslimit = 2 per child3 children totalPROCESSStars & Bars: C(7,2)=21Subtract invalid: -15Apply inclusion-exclusionOUTPUT6Valid distributionsChild 1Child 2Child 3Max 2 candiesMax 2 candiesMax 2 candiesExamples: (0,2,2), (1,1,2), (1,2,1), (2,0,2), (2,1,1), (2,2,1)
Understanding the Visualization
1
Input
n candies and limit per child
2
Process
Count valid distributions using combinatorics
3
Output
Total number of valid ways
Key Takeaway
🎯 Key Insight: Use combinatorics with inclusion-exclusion to efficiently count valid distributions
Asked in
Google 25 Microsoft 20 Meta 15
12.0K Views
Medium Frequency
~25 min Avg. Time
450 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