diff options
-rw-r--r-- | distribute_candies_children2.c | 22 | ||||
-rw-r--r-- | distribute_candies_children2.py | 35 |
2 files changed, 57 insertions, 0 deletions
diff --git a/distribute_candies_children2.c b/distribute_candies_children2.c new file mode 100644 index 0000000..1275d6a --- /dev/null +++ b/distribute_candies_children2.c @@ -0,0 +1,22 @@ +// 2929. Distribute Candies Among Children II +#include "leetcode.h" + +/* + * you are given two positive integers 'n' and 'limit'. return the total number + * of ways to distritube 'n' candies among 3 children such that no child gets + * more than 'limit' candies. + */ + +long long distributeCandies(int n, int limit) { + long long cnt = 0; + for (int i = fmax(0, n - 2 * limit); i <= fmin(limit, n); i++) { + int j = fmin(limit, n - i) - fmax(0, n - i - limit) + 1; + cnt += fmax(0, j); + } + return cnt; +} + +int main() { + printf("%lld\n", distributeCandies(5, 2)); // expect: 3 + printf("%lld\n", distributeCandies(3, 3)); // expect: 10 +} diff --git a/distribute_candies_children2.py b/distribute_candies_children2.py new file mode 100644 index 0000000..6123df8 --- /dev/null +++ b/distribute_candies_children2.py @@ -0,0 +1,35 @@ +# 2929. Distribute Candies Among Children II +from math import comb + +""" +you are given two positive integers 'n' and 'limit'. return the total number +of ways to distritube 'n' candies among 3 children such that no child gets +more than 'limit' candies. +""" + + +class Solution(object): + def distributeCandies(self, n, limit): + """ + :type n: int + :type limit: int + :rtype: int + """ + ans = (n + 2) * (n + 1) // 2 + for i in range(1, 4): + if n - i * (limit + 1) < 0: + break + ans += ( + (-1) ** i + * comb(3, i) + * (n - i * (limit + 1) + 2) + * (n - i * (limit + 1) + 1) + // 2 + ) + return ans + + +if __name__ == "__main__": + obj = Solution() + print(obj.distributeCandies(n=5, limit=2)) + print(obj.distributeCandies(n=3, limit=3)) |