2929. Distribute Candies Among Children II #1754
-
Topics: You are given two positive integers Return the total number of ways to distribute Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the number of ways to distribute Approach
Let's implement this solution in PHP: 2929. Distribute Candies Among Children II <?php
/**
* @param Integer $n
* @param Integer $limit
* @return Integer
*/
function distributeCandies($n, $limit) {
$f = function($x) {
if ($x < 0) {
return 0;
}
return ($x + 2) * ($x + 1) / 2;
};
$ans = $f($n)
- 3 * $f($n - $limit - 1)
+ 3 * $f($n - 2 * $limit - 2)
- $f($n - 3 * $limit - 3);
return (int)$ans;
}
// Test cases
echo distributeCandies(5, 2) . "\n"; // Output: 3
echo distributeCandies(3, 3) . "\n"; // Output: 10
?> Explanation:
This approach efficiently computes the solution using combinatorial mathematics, avoiding the need for brute-force iteration and handling large values within optimal time complexity. |
Beta Was this translation helpful? Give feedback.
We need to determine the number of ways to distribute
n
candies among 3 children such that no child receives more thanlimit
candies. The solution involves using combinatorial mathematics and the inclusion-exclusion principle to efficiently compute the result without iterating through all possible distributions.Approach
Problem Analysis: The problem requires counting the number of non-negative integer solutions to the equation x1 + x2 + x3 = n where 0 ≤ xi ≤ limit for each i.
Combinatorial Insight: The total number of non-negative solutions to the equation without any constraints is given by the stars and bars formula, which is (n + 2)/2. However, we need to subtract the solutions th…