Skip to content

Commit 0be6615

Browse files
committed
Add problem 3452: Sum of Good Numbers
1 parent e810b3e commit 0be6615

3 files changed

Lines changed: 54 additions & 0 deletions

File tree

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2237,6 +2237,7 @@ pub mod problem_3442_maximum_difference_between_even_and_odd_frequency_i;
22372237
pub mod problem_3443_maximum_manhattan_distance_after_k_changes;
22382238
pub mod problem_3446_sort_matrix_by_diagonals;
22392239
pub mod problem_3447_assign_elements_to_groups_with_constraints;
2240+
pub mod problem_3452_sum_of_good_numbers;
22402241

22412242
#[cfg(test)]
22422243
mod test_utilities;
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn sum_of_good_numbers(nums: Vec<i32>, k: i32) -> i32 {
7+
let k = k.cast_unsigned() as usize;
8+
9+
nums.iter()
10+
.enumerate()
11+
.filter_map(|(i, &num)| {
12+
[i.wrapping_sub(k), i + k]
13+
.iter()
14+
.all(|&j| nums.get(j).is_none_or(|&other| num > other))
15+
.then_some(num)
16+
})
17+
.sum()
18+
}
19+
}
20+
21+
// ------------------------------------------------------ snip ------------------------------------------------------ //
22+
23+
impl super::Solution for Solution {
24+
fn sum_of_good_numbers(nums: Vec<i32>, k: i32) -> i32 {
25+
Self::sum_of_good_numbers(nums, k)
26+
}
27+
}
28+
29+
#[cfg(test)]
30+
mod tests {
31+
#[test]
32+
fn test_solution() {
33+
super::super::tests::run::<super::Solution>();
34+
}
35+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
pub mod iterative;
2+
3+
pub trait Solution {
4+
fn sum_of_good_numbers(nums: Vec<i32>, k: i32) -> i32;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [((&[1, 3, 2, 1, 5, 4] as &[_], 2), 12), ((&[2, 1], 1), 2)];
13+
14+
for ((nums, k), expected) in test_cases {
15+
assert_eq!(S::sum_of_good_numbers(nums.to_vec(), k), expected);
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)