Problem Description
Given n candies and 3 children, the goal is to count the total number of ways to distribute the candies such that no child gets more than a specified number (limit) of candies. Each distribution is represented as a triple (a, b, c) with a + b + c = n and each of a, b, c falls in the range [0, limit].
Key Insights
- The distribution must satisfy a + b + c = n and each child receives between 0 and limit candies.
- A brute force approach iterates over all possibilities for two children and determines the third child's candies by subtraction.
- The problem size is small (n, limit ≤ 50), so a double loop (or triple loop) approach is computationally feasible.
- Checking the constraint for the third child is critical to ensure the distribution is valid.
Space and Time Complexity
Time Complexity: O(limit^2) – iterating over two children and computing the third in constant time. Space Complexity: O(1) – constant extra space used.
Solution
The solution uses a nested iteration approach where:
- Loop through all possible values for the first child's candies from 0 to limit.
- For each possibility, loop through all possible values for the second child's candies from 0 to limit.
- Compute the third child's candies as n minus the sum of the first two.
- Check if the third child's candy count is valid (i.e., between 0 and limit).
- Count each valid distribution.
This approach directly enumerates all valid assignments ensuring all constraints are met.