diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 6c51feb..a621879 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -438,3 +438,5 @@ mod p3066_minimum_operations_to_exceed_threshold_value_ii; mod p3095_shortest_subarray_with_or_at_least_k_i; mod p3097_shortest_subarray_with_or_at_least_k_ii; + +mod p3287_find_the_maximum_sequence_value_of_array; diff --git a/src/problem/p3287_find_the_maximum_sequence_value_of_array.rs b/src/problem/p3287_find_the_maximum_sequence_value_of_array.rs new file mode 100644 index 0000000..3691428 --- /dev/null +++ b/src/problem/p3287_find_the_maximum_sequence_value_of_array.rs @@ -0,0 +1,62 @@ +/** + * [3287] Find the Maximum Sequence Value of Array + */ +pub struct Solution {} + +// submission codes start here +use std::collections::HashSet; + +impl Solution { + pub fn max_value(nums: Vec, k: i32) -> i32 { + let k = k as usize; + let length = nums.len(); + let search = |array: &Vec| { + let mut dp = Vec::with_capacity(array.len()); + let mut prev = vec![HashSet::new(); k + 1]; + prev[0].insert(0); + + for i in 0..array.len() { + for j in (0..=(i + 1).min(k - 1)).rev() { + // 使用split_at_mut以通过借用检查 + let (first, second) = prev.split_at_mut(j + 1); + for x in first[j].iter().map(|x| *x | array[i]) { + second[0].insert(x); + } + } + + dp.push(prev[k].clone()); + } + + dp + }; + + let a = search(&nums); + let reversed_nums: Vec = nums.iter().rev().map(|x| x.clone()).collect(); + let b = search(&reversed_nums); + + let mut result = 0; + + for i in k - 1..length - k { + for &a_val in a[i].iter() { + for &b_val in b[length - i - 2].iter() { + result = result.max(a_val ^ b_val); + } + } + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_3287() { + assert_eq!(5, Solution::max_value(vec![2, 6, 7], 1)); + assert_eq!(2, Solution::max_value(vec![4, 2, 5, 6, 7], 2)); + } +}