Distribute Candies Among Children II - 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 distribution must assign a non-negative number of candies to each child, and the sum of all candies distributed must equal n.

Input & Output

Example 1 — Basic Case
$ Input: n = 5, limit = 2
Output: 3
💡 Note: We need to find all (x,y,z) where x+y+z=5 and 0≤x,y,z≤2. The valid distributions are: (1,2,2), (2,1,2), (2,2,1). Total: 3 ways.
Example 2 — Small Input
$ Input: n = 3, limit = 3
Output: 10
💡 Note: All possible distributions are valid since limit=3 ≥ n=3. Total ways = C(3+2,2) = C(5,2) = 10.
Example 3 — Tight Constraint
$ Input: n = 2, limit = 1
Output: 3
💡 Note: Valid ways: (0,1,1), (1,0,1), (1,1,0). Each child gets at most 1 candy and total is 2.

Constraints

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

Visualization

Tap to expand
Distribute Candies Among Children II INPUT 3 Children, distribute n candies C1 0-2 C2 0-2 C3 0-2 Each child: max 'limit' candies Total Candies to Distribute n = 5 candies limit = 2 max per child Sum must equal n exactly ALGORITHM STEPS 1 Inclusion-Exclusion Count all, subtract invalid 2 Total without limit C(n+2, 2) = C(7,2) = 21 3 Subtract violations One child exceeds limit 4 Add back overlaps Two+ children exceed Formula: Total - (A + B + C) + (AB + AC + BC) - (ABC) A,B,C = child exceeds limit 21 - 18 + 0 - 0 = 3 Stars and bars + inclusion-exclusion FINAL RESULT Valid Distributions: Distribution 1 2 2 1 Distribution 2 2 1 2 Distribution 3 1 2 2 OUTPUT 3 [OK] 3 valid ways found All sums = 5, all values <= 2 Key Insight: Use Inclusion-Exclusion Principle with Stars and Bars combinatorics. Total ways = C(n+2,2). Subtract cases where any child exceeds limit using substitution: if child gets > limit, replace their count with (count - limit - 1). TutorialsPoint - Distribute Candies Among Children II | Optimal Solution (Inclusion-Exclusion)
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~25 min Avg. Time
345 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