Skip to content

Commit

Permalink
Add problem 2369: Check if There is a Valid Partition For The Array
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Dec 26, 2024
1 parent d1ed1f7 commit 9e6a7b4
Show file tree
Hide file tree
Showing 3 changed files with 59 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 @@ -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)]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

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

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod dynamic_programming;

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

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

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

0 comments on commit 9e6a7b4

Please sign in to comment.