diff --git a/src/lib.rs b/src/lib.rs index 996bc5af..c4edd077 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1472,6 +1472,7 @@ pub mod problem_1995_count_special_quadruplets; pub mod problem_1996_the_number_of_weak_characters_in_the_game; pub mod problem_2000_reverse_prefix_of_word; pub mod problem_2001_number_of_pairs_of_interchangeable_rectangles; +pub mod problem_2002_maximum_product_of_the_length_of_two_palindromic_subsequences; pub mod problem_2006_count_number_of_pairs_with_absolute_difference_k; pub mod problem_2007_find_original_array_from_doubled_array; pub mod problem_2011_final_value_of_variable_after_performing_operations; diff --git a/src/problem_2002_maximum_product_of_the_length_of_two_palindromic_subsequences/dynamic_programming.rs b/src/problem_2002_maximum_product_of_the_length_of_two_palindromic_subsequences/dynamic_programming.rs new file mode 100644 index 00000000..7f36b517 --- /dev/null +++ b/src/problem_2002_maximum_product_of_the_length_of_two_palindromic_subsequences/dynamic_programming.rs @@ -0,0 +1,51 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn max_product(s: String) -> i32 { + let s = s.as_bytes(); + let n = s.len(); + let mut cache = vec![0_u8; 1 << n].into_boxed_slice(); + let full_mask = cache.len() - 1; + + for mask in 1..cache.len() { + cache[mask] = if mask.is_power_of_two() { + 1 + } else { + let first_index = mask.trailing_zeros(); + let last_index = usize::BITS - 1 - mask.leading_zeros(); + + if s[first_index as usize] == s[last_index as usize] { + cache[mask ^ (1 << first_index) ^ (1 << last_index)] + 2 + } else { + cache[mask ^ (1 << first_index)].max(cache[mask ^ (1 << last_index)]) + } + }; + } + + let mut result = 0_u8; + + for mask in 1..=(full_mask >> 1) { + result = result.max(cache[mask] * cache[full_mask ^ mask]); + } + + i32::from(result) + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn max_product(s: String) -> i32 { + Self::max_product(s) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2002_maximum_product_of_the_length_of_two_palindromic_subsequences/mod.rs b/src/problem_2002_maximum_product_of_the_length_of_two_palindromic_subsequences/mod.rs new file mode 100644 index 00000000..65ced76e --- /dev/null +++ b/src/problem_2002_maximum_product_of_the_length_of_two_palindromic_subsequences/mod.rs @@ -0,0 +1,18 @@ +pub mod dynamic_programming; + +pub trait Solution { + fn max_product(s: String) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [("leetcodecom", 9), ("bb", 1), ("accbcaxxcxx", 25)]; + + for (s, expected) in test_cases { + assert_eq!(S::max_product(s.to_string()), expected); + } + } +}