Skip to content

Commit 91a51e9

Browse files
committed
Sync LeetCode submission Runtime - 4 ms (13.43%), Memory - 17.7 MB (62.62%)
1 parent 0ededa3 commit 91a51e9

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<p>You are given two positive integers <code>n</code> and <code>limit</code>.</p>
2+
3+
<p>Return <em>the <strong>total number</strong> of ways to distribute </em><code>n</code> <em>candies among </em><code>3</code><em> children such that no child gets more than </em><code>limit</code><em> candies.</em></p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> n = 5, limit = 2
10+
<strong>Output:</strong> 3
11+
<strong>Explanation:</strong> 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).
12+
</pre>
13+
14+
<p><strong class="example">Example 2:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> n = 3, limit = 3
18+
<strong>Output:</strong> 10
19+
<strong>Explanation:</strong> 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).
20+
</pre>
21+
22+
<p>&nbsp;</p>
23+
<p><strong>Constraints:</strong></p>
24+
25+
<ul>
26+
<li><code>1 &lt;= n &lt;= 10<sup>8</sup></code></li>
27+
<li><code>1 &lt;= limit &lt;= 10<sup>8</sup></code></li>
28+
</ul>
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
def cal(x):
2+
if x < 0:
3+
return 0
4+
return x * (x - 1) // 2
5+
6+
7+
class Solution:
8+
def distributeCandies(self, n: int, limit: int) -> int:
9+
return (
10+
cal(n + 2)
11+
- 3 * cal(n - limit + 1)
12+
+ 3 * cal(n - (limit + 1) * 2 + 2)
13+
- cal(n - 3 * (limit + 1) + 2)
14+
)

0 commit comments

Comments
 (0)