Problem Description
Given n candies, count the total number of distributions of these candies among 3 children such that every child gets no more than limit candies. A distribution is defined by an ordered triple (a, b, c) where a + b + c = n and 0 ≤ a, b, c ≤ limit.
Key Insights
- Notice that without the upper bound, the number of solutions (non-negative integer triples) is given by C(n+2, 2).
- The constraint that each child can receive at most limit candies can be handled via the Inclusion-Exclusion Principle.
- Specifically, subtract the distributions where at least one child exceeds limit, add back those where at least two exceed, and so on.
- The formula becomes: ans = Σ from k=0 to 3 [(-1)^k * C(3, k) * C(n - k*(limit+1) + 2, 2)] for terms where n - k*(limit+1) ≥ 0.
- If n > 3*limit then no distribution is possible.
Space and Time Complexity
Time Complexity: O(1) since the solution uses a closed-form mathematical expression. Space Complexity: O(1) as only a constant amount of extra space is used.
Solution
We leverage combinatorics to count the distributions. The number of ways to distribute n candies among 3 children without restrictions is C(n+2, 2). However, since each child can receive at most limit candies, we need to subtract those distributions where one or more children exceed this limit. Using the Inclusion-Exclusion Principle, for every k (from 0 to 3), we subtract or add back the count of distributions where exactly k children get more than limit candies. We perform a variable substitution for a child that exceeds the limit (by subtracting limit+1 from its candy count), and then count the number of solutions for the adjusted total, ensuring we only count valid cases where the remaining candies is non-negative. This approach gives us a formula that calculates the result in constant time without iterating over all possible distributions.
Code Solutions
Below are implementations in Python, JavaScript, C++, and Java with detailed inline comments.