From d386f346f34dca01cba70b8ed7a747b41f424c27 Mon Sep 17 00:00:00 2001 From: Walker Smith Date: Sun, 27 Jul 2025 11:51:08 -0400 Subject: [PATCH] solve problem --- .../README.md | 21 ++++++++++ .../index.js | 39 +++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 leet-code/2928-distribute-candies-among-children-1/README.md create mode 100644 leet-code/2928-distribute-candies-among-children-1/index.js diff --git a/leet-code/2928-distribute-candies-among-children-1/README.md b/leet-code/2928-distribute-candies-among-children-1/README.md new file mode 100644 index 0000000..37ac80b --- /dev/null +++ b/leet-code/2928-distribute-candies-among-children-1/README.md @@ -0,0 +1,21 @@ +# 2928-distribute-candies-among-children-1 + +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. + +Example 1: + +Input: n = 5, limit = 2 +Output: 3 +Explanation: 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). +Example 2: + +Input: n = 3, limit = 3 +Output: 10 +Explanation: 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). + +Constraints: + +1 <= n <= 50 +1 <= limit <= 50 diff --git a/leet-code/2928-distribute-candies-among-children-1/index.js b/leet-code/2928-distribute-candies-among-children-1/index.js new file mode 100644 index 0000000..9c3269e --- /dev/null +++ b/leet-code/2928-distribute-candies-among-children-1/index.js @@ -0,0 +1,39 @@ +/** + * @param {number} n + * @param {number} limit + * @description |A ∪ B ∪ C| = |A| + |B| + |C| + - |A ∩ B| - |A ∩ C| - |B ∩ C| + + |A ∩ B ∩ C| + * @return {number} + */ +var distributeCandies = function(n, limit) { + const numberOfAllCombinations = nChooseK(n + 2, 2) + const numberOfDistinctChildren = 3 + const numberOfCombinationsSuchThatOneChildExceedsLimit = n - limit + 1 >= 0 + ? numberOfDistinctChildren * nChooseK(n - limit + 1, 2) + : 0 + const numberOfDistinctPairsOfChildren = 3 + const numberOfCombinationsSuchThatTwoChildrenExceedsLimit = n - limit *2 >= 0 + ? numberOfDistinctPairsOfChildren * nChooseK(n - limit * 2, 2) + : 0 + const numberOfCombinationsSuchThatThreeChildrenExceedsLimit = n - limit * 3 -1 >= 0 + ? nChooseK(n - limit * 3 - 1, 2) + : 0 + + return numberOfAllCombinations + - numberOfCombinationsSuchThatOneChildExceedsLimit + + numberOfCombinationsSuchThatTwoChildrenExceedsLimit + - numberOfCombinationsSuchThatThreeChildrenExceedsLimit +}; + +function nChooseK(n, k) { + if (k < 0 || k > n) return 0; + if (k === 0 || k === n) return 1; + k = Math.min(k, n - k); + let result = 1; + for (let i = 1; i <= k; i++) { + result *= n--; + result /= i; + } + return result; +} \ No newline at end of file