From 8bc2e0d3478637a90e685cc8c8b7a3656c3d02f3 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Fri, 1 Mar 2024 08:23:03 +0800 Subject: [PATCH] 20240301 Finished --- src/problem/mod.rs | 3 +- ...here_is_a_valid_partition_for_the_array.rs | 53 +++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 src/problem/p2369_check_if_there_is_a_valid_partition_for_the_array.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 02a6878..6fb46b0 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -59,4 +59,5 @@ mod p938_range_sum_of_bst; mod p889_construct_binary_tree_from_preorder_and_postorder_traversal; mod p2867_count_valid_paths_in_a_tree; mod p2673_make_costs_of_paths_equal_in_a_binary_tree; -mod p2581_count_number_of_possible_root_nodes; \ No newline at end of file +mod p2581_count_number_of_possible_root_nodes; +mod p2369_check_if_there_is_a_valid_partition_for_the_array; \ No newline at end of file diff --git a/src/problem/p2369_check_if_there_is_a_valid_partition_for_the_array.rs b/src/problem/p2369_check_if_there_is_a_valid_partition_for_the_array.rs new file mode 100644 index 0000000..3a95702 --- /dev/null +++ b/src/problem/p2369_check_if_there_is_a_valid_partition_for_the_array.rs @@ -0,0 +1,53 @@ +/** + * [2369] Check if There is a Valid Partition For The Array + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn valid_partition(nums: Vec) -> bool { + let mut dp = vec![false; nums.len()]; + dp[1] = nums[0] == nums[1]; + + for i in 2..nums.len() { + // 首先判断用两个相同的值 + dp[i] = dp[i - 2] && nums[i] == nums[i - 1]; + + if dp[i] { + continue; + } + + // 然后判断三个相同的值 + if i >= 3 { + dp[i] = dp[i - 3] + && ((nums[i - 2] == nums[i - 1] && nums[i - 1] == nums[i]) + || (nums[i - 2] + 1 == nums[i - 1] && nums[i - 1] + 1 == nums[i])); + } else { + dp[i] = (nums[i - 2] == nums[i - 1] && nums[i - 1] == nums[i]) + || (nums[i - 2] + 1 == nums[i - 1] && nums[i - 1] + 1 == nums[i]); + } + } + + dp[nums.len() - 1] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2369() { + assert!(Solution::valid_partition(vec![4, 4, 4, 5, 6])); + assert!(!Solution::valid_partition(vec![4, 4, 4, 5])); + assert!(Solution::valid_partition(vec![ + 803201, 803201, 803201, 803201, 803202, 803203 + ])); + assert!(!Solution::valid_partition(vec![ + 993335, 993336, 993337, 993338, 993339, 993340, 993341 + ])); + } +}