Skip to content

Commit 33324b2

Browse files
committed
Add problem 2760: Longest Even Odd Subarray With Threshold
1 parent 93b9054 commit 33324b2

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1958,6 +1958,7 @@ pub mod problem_2734_lexicographically_smallest_string_after_substring_operation
19581958
pub mod problem_2739_total_distance_traveled;
19591959
pub mod problem_2740_find_the_value_of_the_partition;
19601960
pub mod problem_2744_find_maximum_number_of_string_pairs;
1961+
pub mod problem_2760_longest_even_odd_subarray_with_threshold;
19611962

19621963
#[cfg(test)]
19631964
mod test_utilities;
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
pub mod sliding_window;
2+
3+
pub trait Solution {
4+
fn longest_alternating_subarray(nums: Vec<i32>, threshold: 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 = [
13+
((&[3, 2, 5, 4] as &[_], 5), 3),
14+
((&[1, 2], 2), 1),
15+
((&[2, 3, 4, 5], 4), 3),
16+
((&[8, 10, 7, 8, 3], 9), 2),
17+
];
18+
19+
for ((nums, threshold), expected) in test_cases {
20+
assert_eq!(S::longest_alternating_subarray(nums.to_vec(), threshold), expected);
21+
}
22+
}
23+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn longest_alternating_subarray(nums: Vec<i32>, threshold: i32) -> i32 {
7+
let mut result = 0;
8+
let mut length = 0;
9+
let mut prev_is_even = false;
10+
11+
for num in nums {
12+
if num <= threshold {
13+
let is_even = num % 2 == 0;
14+
15+
if is_even == prev_is_even {
16+
result = result.max(length);
17+
length = i32::from(is_even);
18+
} else {
19+
length += 1;
20+
}
21+
22+
prev_is_even = is_even;
23+
} else {
24+
result = result.max(length);
25+
length = 0;
26+
prev_is_even = false;
27+
}
28+
}
29+
30+
result.max(length)
31+
}
32+
}
33+
34+
// ------------------------------------------------------ snip ------------------------------------------------------ //
35+
36+
impl super::Solution for Solution {
37+
fn longest_alternating_subarray(nums: Vec<i32>, threshold: i32) -> i32 {
38+
Self::longest_alternating_subarray(nums, threshold)
39+
}
40+
}
41+
42+
#[cfg(test)]
43+
mod tests {
44+
#[test]
45+
fn test_solution() {
46+
super::super::tests::run::<super::Solution>();
47+
}
48+
}

0 commit comments

Comments
 (0)