diff --git a/src/problem/mod.rs b/src/problem/mod.rs index ddeb738..bd6cbf4 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -24,4 +24,5 @@ mod p2171_removing_minimum_number_of_magic_beans; mod p2809_minimum_time_to_make_array_sum_at_most_x; mod p2788_split_strings_by_separator; mod p410_split_array_largest_sum; -mod p670_maximum_swap; \ No newline at end of file +mod p670_maximum_swap; +mod p2765_longest_alternating_subarray; \ No newline at end of file diff --git a/src/problem/p2765_longest_alternating_subarray.rs b/src/problem/p2765_longest_alternating_subarray.rs new file mode 100644 index 0000000..86fc0e0 --- /dev/null +++ b/src/problem/p2765_longest_alternating_subarray.rs @@ -0,0 +1,40 @@ +/** + * [2765] Longest Alternating Subarray + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn alternating_subarray(nums: Vec) -> i32 { + let mut result = -1; + + for i in 0..nums.len() { + for j in i + 1..nums.len() { + if nums[j] - nums[i] != ((j - i) % 2) as i32 { + break; + } + + result = result.max((j - i + 1) as i32); + } + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2765() { + assert_eq!(Solution::alternating_subarray(vec![2,3,4,3,4]), 4); + assert_eq!(Solution::alternating_subarray(vec![4,5,6]), 2); + assert_eq!(Solution::alternating_subarray(vec![21,9,5]), -1); + assert_eq!(Solution::alternating_subarray(vec![21,22]), 2); + } +}