[LeetCode] Distribute Candies Among Children II

2929. Distribute Candies Among Children II

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
long long distributeCandies(int n, int limit) {
long long res = 0;
for(long long i = 0; i <= limit; i++) {
long long now = n - i;
if(now < 0) break;
if(now <= limit) res += (now + 1);
else if(now > 2 * limit) continue;
else {
res += (limit - (now - limit) + 1);
}
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/11/12/PS/LeetCode/distribute-candies-among-children-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.