Distribute Candies Among Children III — LeetCode 2927 Python Solution
- Problem
- #2927
- 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 2927. Distribute Candies Among Children III 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 2927. Distribute Candies Among Children III?
- LeetCode 2927. Distribute Candies Among Children III is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2927. Distribute Candies Among Children III?
- The Python solution on this page runs in O(1).
- What is the space complexity of LeetCode 2927. Distribute Candies Among Children III?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2927. Distribute Candies Among Children III cover?
- LeetCode 2927. Distribute Candies Among Children III is tagged Math and Combinatorics on LeetCode.
- Is LeetCode 2927. Distribute Candies Among Children III a premium problem?
- Yes. LeetCode 2927. Distribute Candies Among Children III is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.