[LeetCode] Distribute Candies Among Children I

2928. Distribute Candies Among Children I

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:
int distributeCandies(int n, int limit) {
int 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-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.