Distribute Candies Among Children II Problem
#2929
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2929.
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.
Example 1:
Input: n = 5, limit = 2
Output: 3
Explanation: There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).
Example 2:
Input: n = 3, limit = 3
Output: 10
Explanation: There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (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) and (3, 0, 0).
Constraints:
1 <= n <= 10^61 <= limit <= 10^6
Solution
Approach: Combinatorics + Inclusion-Exclusion
Count the ways to give n candies to 3 children with each getting between 0 and limit.
Without the limit, the number of non-negative solutions of a + b + c = n is C(n + 2, 2). Now remove the bad cases:
- A given child gets more than
limit: give that childlimit + 1candies first and distribute the remainingn - limit - 1freely, which givesC(n - limit + 1, 2). There are 3 children, so subtract3 * C(n - limit + 1, 2). - Two children both exceed
limitwere subtracted twice, so add them back:3 * C(n - 2 * limit, 2). This applies only whenn - 2 * limit >= 2. - If
n > 3 * limit, the answer is 0.
Complexity: O(1) time and space.
from math import comb
class Solution:
def distributeCandies(self, n: int, limit: int) -> int:
if n > 3 * limit:
return 0
ans = comb(n + 2, 2)
if n > limit:
ans -= 3 * comb(n - limit + 1, 2)
if n - 2 >= 2 * limit:
ans += 3 * comb(n - 2 * limit, 2)
return ans