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 Candies Among Children III INPUT CANDIES n = 5 Child 1 Child 2 Child 3 n = 5 (candies) limit = 2 (max each) children = 3 ALGORITHM STEPS 1 Inclusion-Exclusion Count all distributions 2 Stars and Bars C(n+2, 2) = C(7,2) = 21 3 Subtract Violations Remove child > limit 4 Add Back Overlaps Fix double-counting Formula: Total = C(n+2,2) - 3*C(n-limit-1+2,2) + 3*C(n-2*(limit+1)+2,2) - C(n-3*(limit+1)+2,2) = 21 - 18 + 3 - 0 = 6 FINAL RESULT All 6 Valid Distributions: (0, 2, 2) (1, 2, 2) (2, 0, 2) (2, 1, 2) (2, 2, 0) (2, 2, 1) Constraints Verified: Each child: 0 to 2 -- OK Sum = 5 -- OK OUTPUT 6 6 ways to distribute! Key Insight: The Inclusion-Exclusion principle transforms this counting problem into O(1) time complexity. Instead of iterating through all combinations, we use combinatorics: count all ways (Stars and Bars), then subtract invalid cases where any child exceeds the limit, adding back over-subtracted overlaps. TutorialsPoint - Distribute Candies Among Children III | Optimal Solution (Inclusion-Exclusion) Time: O(1) | Space: O(1)
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