diff --git a/src/lib.rs b/src/lib.rs index 1b9adcf..10bda4b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -346,6 +346,7 @@ pub mod problem_0507_perfect_number; pub mod problem_0513_find_bottom_left_tree_value; pub mod problem_0515_find_largest_value_in_each_tree_row; pub mod problem_0523_continuous_subarray_sum; +pub mod problem_0525_contiguous_array; pub mod problem_0530_minimum_absolute_difference_in_bst; pub mod problem_0532_k_diff_pairs_in_an_array; pub mod problem_0537_complex_number_multiplication; diff --git a/src/problem_0525_contiguous_array/iterative.rs b/src/problem_0525_contiguous_array/iterative.rs new file mode 100644 index 0000000..7aaaeea --- /dev/null +++ b/src/problem_0525_contiguous_array/iterative.rs @@ -0,0 +1,39 @@ +pub struct Solution; + +use std::collections::HashMap; + +impl Solution { + pub fn find_max_length(nums: Vec) -> i32 { + let mut map = HashMap::with_capacity(nums.len()); + map.insert(0, 0); + + let mut result = 0; + let mut count = [0, 0]; + + for (num, idx) in nums.into_iter().zip(1..) { + count[num as usize] += 1; + let key = count[1] - count[0]; + if let Some(&prev) = map.get(&key) { + result = result.max(idx - prev); + } else { + map.insert(key, idx); + } + } + + result + } +} + +impl super::Solution for Solution { + fn find_max_length(nums: Vec) -> i32 { + Self::find_max_length(nums) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_0525_contiguous_array/mod.rs b/src/problem_0525_contiguous_array/mod.rs new file mode 100644 index 0000000..cac7836 --- /dev/null +++ b/src/problem_0525_contiguous_array/mod.rs @@ -0,0 +1,18 @@ +pub mod iterative; + +pub trait Solution { + fn find_max_length(nums: Vec) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [(&[0, 1] as &[_], 2), (&[0, 1, 0], 2)]; + + for (nums, expected) in test_cases { + assert_eq!(S::find_max_length(nums.to_vec()), expected); + } + } +}