20240301 Finished

This commit is contained in:
jackfiled 2024-03-01 08:23:03 +08:00
parent 08da695ca3
commit 8bc2e0d347
2 changed files with 55 additions and 1 deletions

View File

@ -60,3 +60,4 @@ mod p889_construct_binary_tree_from_preorder_and_postorder_traversal;
mod p2867_count_valid_paths_in_a_tree; mod p2867_count_valid_paths_in_a_tree;
mod p2673_make_costs_of_paths_equal_in_a_binary_tree; mod p2673_make_costs_of_paths_equal_in_a_binary_tree;
mod p2581_count_number_of_possible_root_nodes; mod p2581_count_number_of_possible_root_nodes;
mod p2369_check_if_there_is_a_valid_partition_for_the_array;

View File

@ -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<i32>) -> 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
]));
}
}