From 0e5ab485d55a41eee16385493ef953e6ed75afd3 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Tue, 23 Jan 2024 11:16:04 +0800 Subject: [PATCH] 20240123 Finished --- src/problem/mod.rs | 3 +- .../p2765_longest_alternating_subarray.rs | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 src/problem/p2765_longest_alternating_subarray.rs 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); + } +}