Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions leet-code/2928-distribute-candies-among-children-1/README.md
Original file line number Diff line number Diff line change
@@ -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
39 changes: 39 additions & 0 deletions leet-code/2928-distribute-candies-among-children-1/index.js
Original file line number Diff line number Diff line change
@@ -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;
}