Skip to content

Commit e948f31

Browse files
committed
Add problem 2765: Longest Alternating Subarray
1 parent 9594885 commit e948f31

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1960,6 +1960,7 @@ pub mod problem_2740_find_the_value_of_the_partition;
19601960
pub mod problem_2744_find_maximum_number_of_string_pairs;
19611961
pub mod problem_2760_longest_even_odd_subarray_with_threshold;
19621962
pub mod problem_2761_prime_pairs_with_target_sum;
1963+
pub mod problem_2765_longest_alternating_subarray;
19631964

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

0 commit comments

Comments
 (0)