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 Candies Among Children I INPUT Child 1 Child 2 Child 3 5 Candies to Distribute n 5 limit 2 Each child: 0 to 2 candies Total must equal 5 c1 + c2 + c3 = n ALGORITHM STEPS 1 Iterate c1: 0 to limit First child gets 0, 1, or 2 2 Iterate c2: 0 to limit Second child gets 0, 1, or 2 3 Calculate c3 = n - c1 - c2 Remaining for third child 4 Check: 0 <= c3 <= limit If valid, count++ Valid Combinations Found: (1, 2, 2) OK 1+2+2=5 (2, 1, 2) OK 2+1+2=5 (2, 2, 1) OK 2+2+1=5 (0, 2, 2) X c3=3 > limit FINAL RESULT 2 1 2 Example: (2, 1, 2) Output: 3 3 Valid Distributions: (1, 2, 2) (2, 1, 2) (2, 2, 1) Key Insight: Use nested loops for c1 and c2 (0 to min(limit, n)), then calculate c3 = n - c1 - c2. A distribution is valid only if c3 is within [0, limit]. Time complexity: O(limit^2) or O(n^2). TutorialsPoint - Distribute Candies Among Children I | Optimal Solution
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