[LeetCode] Distribute Candies Among Children III

2927. Distribute Candies Among Children III

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
18
19
20
21
22
class Solution {
public:
long long distributeCandies(int n, int limit) {
if(limit * 3 < n) return 0;
long long res = 0, hold = min(limit, n);
for(long long i = max(0, n - 2 * limit); i <= hold; i++) {
long long x = n - i;
if(x <= limit) {
long long rem = hold - i + 1;
res += rem * (2 * x - rem + 1) / 2 + rem;
break;
}
else {
long long l = i, r = min(n - limit - 1ll, hold), cnt = r - l + 1;
res += 2 * limit * cnt + cnt;
res -= cnt * (n - l + n - r) / 2;
i = n - limit - 1;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/01/13/PS/LeetCode/distribute-candies-among-children-iii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.