diff --git a/src/lib.rs b/src/lib.rs index f8f2b2c8..6f90eb77 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1763,6 +1763,7 @@ pub mod problem_2365_task_scheduler_ii; pub mod problem_2366_minimum_replacements_to_sort_the_array; pub mod problem_2367_number_of_arithmetic_triplets; pub mod problem_2368_reachable_nodes_with_restrictions; +pub mod problem_2369_check_if_there_is_a_valid_partition_for_the_array; pub mod problem_2370_longest_ideal_subsequence; #[cfg(test)] diff --git a/src/problem_2369_check_if_there_is_a_valid_partition_for_the_array/dynamic_programming.rs b/src/problem_2369_check_if_there_is_a_valid_partition_for_the_array/dynamic_programming.rs new file mode 100644 index 00000000..53644401 --- /dev/null +++ b/src/problem_2369_check_if_there_is_a_valid_partition_for_the_array/dynamic_programming.rs @@ -0,0 +1,40 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn valid_partition(nums: Vec) -> bool { + let mut cache = (false, false, true); + let mut prev = (0, 0); + + for num in nums { + cache = ( + cache.1, + cache.2, + (cache.1 && prev.1 == num) + || (cache.0 + && ((prev.0 == prev.1 && prev.1 == num) || (prev.0 + 1 == prev.1 && prev.1 + 1 == num))), + ); + + prev = (prev.1, num); + } + + cache.2 + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn valid_partition(nums: Vec) -> bool { + Self::valid_partition(nums) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2369_check_if_there_is_a_valid_partition_for_the_array/mod.rs b/src/problem_2369_check_if_there_is_a_valid_partition_for_the_array/mod.rs new file mode 100644 index 00000000..88b7f2c9 --- /dev/null +++ b/src/problem_2369_check_if_there_is_a_valid_partition_for_the_array/mod.rs @@ -0,0 +1,18 @@ +pub mod dynamic_programming; + +pub trait Solution { + fn valid_partition(nums: Vec) -> bool; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [(&[4, 4, 4, 5, 6] as &[_], true), (&[1, 1, 1, 2], false)]; + + for (nums, expected) in test_cases { + assert_eq!(S::valid_partition(nums.to_vec()), expected); + } + } +}