From 46b152ae9e02b15a3aed8f326b4a48860a766fea Mon Sep 17 00:00:00 2001 From: yanglbme Date: Sun, 1 Jun 2025 09:35:06 +0800 Subject: [PATCH] feat: add solutions to lc problem: No.2929 No.2929. Distribute Candies Among Children II --- .../README.md | 24 +++++++++++++++++++ .../README_EN.md | 24 +++++++++++++++++++ .../Solution.rs | 19 +++++++++++++++ 3 files changed, 67 insertions(+) create mode 100644 solution/2900-2999/2929.Distribute Candies Among Children II/Solution.rs diff --git a/solution/2900-2999/2929.Distribute Candies Among Children II/README.md b/solution/2900-2999/2929.Distribute Candies Among Children II/README.md index 36ac2fc4a6239..19d5ed31fe358 100644 --- a/solution/2900-2999/2929.Distribute Candies Among Children II/README.md +++ b/solution/2900-2999/2929.Distribute Candies Among Children II/README.md @@ -172,6 +172,30 @@ function distributeCandies(n: number, limit: number): number { } ``` +#### Rust + +```rust +impl Solution { + pub fn distribute_candies(n: i32, limit: i32) -> i64 { + if n > 3 * limit { + return 0; + } + let mut ans = Self::comb2(n + 2); + if n > limit { + ans -= 3 * Self::comb2(n - limit + 1); + } + if n - 2 >= 2 * limit { + ans += 3 * Self::comb2(n - 2 * limit); + } + ans + } + + fn comb2(n: i32) -> i64 { + (n as i64) * (n as i64 - 1) / 2 + } +} +``` + diff --git a/solution/2900-2999/2929.Distribute Candies Among Children II/README_EN.md b/solution/2900-2999/2929.Distribute Candies Among Children II/README_EN.md index e6da8d83b3c2b..caf6d50251447 100644 --- a/solution/2900-2999/2929.Distribute Candies Among Children II/README_EN.md +++ b/solution/2900-2999/2929.Distribute Candies Among Children II/README_EN.md @@ -170,6 +170,30 @@ function distributeCandies(n: number, limit: number): number { } ``` +#### Rust + +```rust +impl Solution { + pub fn distribute_candies(n: i32, limit: i32) -> i64 { + if n > 3 * limit { + return 0; + } + let mut ans = Self::comb2(n + 2); + if n > limit { + ans -= 3 * Self::comb2(n - limit + 1); + } + if n - 2 >= 2 * limit { + ans += 3 * Self::comb2(n - 2 * limit); + } + ans + } + + fn comb2(n: i32) -> i64 { + (n as i64) * (n as i64 - 1) / 2 + } +} +``` + diff --git a/solution/2900-2999/2929.Distribute Candies Among Children II/Solution.rs b/solution/2900-2999/2929.Distribute Candies Among Children II/Solution.rs new file mode 100644 index 0000000000000..c5c80fd0398b1 --- /dev/null +++ b/solution/2900-2999/2929.Distribute Candies Among Children II/Solution.rs @@ -0,0 +1,19 @@ +impl Solution { + pub fn distribute_candies(n: i32, limit: i32) -> i64 { + if n > 3 * limit { + return 0; + } + let mut ans = Self::comb2(n + 2); + if n > limit { + ans -= 3 * Self::comb2(n - limit + 1); + } + if n - 2 >= 2 * limit { + ans += 3 * Self::comb2(n - 2 * limit); + } + ans + } + + fn comb2(n: i32) -> i64 { + (n as i64) * (n as i64 - 1) / 2 + } +}