Skip to content

Commit

Permalink
Add problem 2002: Maximum Product of the Length of Two Palindromic Su…
Browse files Browse the repository at this point in the history
…bsequences
  • Loading branch information
EFanZh committed Jun 10, 2024
1 parent f0f2904 commit 48683fc
Show file tree
Hide file tree
Showing 3 changed files with 70 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 @@ -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;
Expand Down
Original file line number Diff line number Diff line change
@@ -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::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -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<S: Solution>() {
let test_cases = [("leetcodecom", 9), ("bb", 1), ("accbcaxxcxx", 25)];

for (s, expected) in test_cases {
assert_eq!(S::max_product(s.to_string()), expected);
}
}
}

0 comments on commit 48683fc

Please sign in to comment.