Problem
You are given two positive integersn and limit.
Return the total number of ways to distribute n candies among 3 children such that no child gets more than limit candies.
Examples
Constraints
1 <= n <= 10^61 <= limit <= 10^6
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 2929 with 18 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 2929 # by problem number
lcpy gen -s distribute_candies_among_children_ii # by problem name
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.
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).
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).
1 <= n <= 10^61 <= limit <= 10^6class Solution:
# Time: O(1)
# Space: O(1)
def distribute_candies(self, n: int, limit: int) -> int:
def capped_ways(total: int) -> int:
# Ways for 3 non-negative parts summing to `total`, ignoring the cap:
# C(total + 2, 2); 0 when no composition exists.
return (total + 2) * (total + 1) // 2 if total >= 0 else 0
return (
capped_ways(n)
- 3 * capped_ways(n - (limit + 1))
+ 3 * capped_ways(n - 2 * (limit + 1))
- capped_ways(n - 3 * (limit + 1))
)
| Time | Space |
|---|---|
| O(1) | O(1) |