Distribute Candies Among Children II — LeetCode 2929 Python Solution
- Problem
- #2929
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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
- 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).
Python solution
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(1) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2929. Distribute Candies Among Children II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Combinatorics.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2929. Distribute Candies Among Children II?
- LeetCode 2929. Distribute Candies Among Children II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2929. Distribute Candies Among Children II?
- The Python solution on this page runs in O(1).
- What is the space complexity of LeetCode 2929. Distribute Candies Among Children II?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2929. Distribute Candies Among Children II cover?
- LeetCode 2929. Distribute Candies Among Children II is tagged Math, Combinatorics and Enumeration on LeetCode.