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 + } +}