Skip to content

Commit

Permalink
Add problem 0525: Contiguous Array
Browse files Browse the repository at this point in the history
  • Loading branch information
Spxg committed May 31, 2024
1 parent 83a4fe5 commit 6b6ff10
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
39 changes: 39 additions & 0 deletions src/problem_0525_contiguous_array/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
pub struct Solution;

use std::collections::HashMap;

impl Solution {
pub fn find_max_length(nums: Vec<i32>) -> 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>) -> i32 {
Self::find_max_length(nums)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
18 changes: 18 additions & 0 deletions src/problem_0525_contiguous_array/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod iterative;

pub trait Solution {
fn find_max_length(nums: Vec<i32>) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
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);
}
}
}

0 comments on commit 6b6ff10

Please sign in to comment.