diff --git a/src/lib.rs b/src/lib.rs index 88c2a27c..9dbb00d0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1625,6 +1625,7 @@ pub mod problem_2197_replace_non_coprime_numbers_in_array; pub mod problem_2200_find_all_k_distant_indices_in_an_array; pub mod problem_2202_maximize_the_topmost_element_after_k_moves; pub mod problem_2206_divide_array_into_equal_pairs; +pub mod problem_2207_maximize_number_of_subsequences_in_a_string; pub mod problem_2208_minimum_operations_to_halve_array_sum; pub mod problem_2210_count_hills_and_valleys_in_an_array; pub mod problem_2215_find_the_difference_of_two_arrays; diff --git a/src/problem_2207_maximize_number_of_subsequences_in_a_string/greedy.rs b/src/problem_2207_maximize_number_of_subsequences_in_a_string/greedy.rs new file mode 100644 index 00000000..e047657f --- /dev/null +++ b/src/problem_2207_maximize_number_of_subsequences_in_a_string/greedy.rs @@ -0,0 +1,36 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn maximum_subsequence_count(text: String, pattern: String) -> i64 { + let [left, right]: [_; 2] = pattern.into_bytes().try_into().ok().unwrap(); + let mut left_count = 0_u64; + let mut right_count = 0_u64; + let mut result = 0; + + for c in text.into_bytes() { + result += left_count * u64::from(c == right); + left_count += u64::from(c == left); + right_count += u64::from(c == right); + } + + (result + left_count.max(right_count)) as _ + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn maximum_subsequence_count(text: String, pattern: String) -> i64 { + Self::maximum_subsequence_count(text, pattern) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2207_maximize_number_of_subsequences_in_a_string/mod.rs b/src/problem_2207_maximize_number_of_subsequences_in_a_string/mod.rs new file mode 100644 index 00000000..911c0f92 --- /dev/null +++ b/src/problem_2207_maximize_number_of_subsequences_in_a_string/mod.rs @@ -0,0 +1,21 @@ +pub mod greedy; + +pub trait Solution { + fn maximum_subsequence_count(text: String, pattern: String) -> i64; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [(("abdcdbc", "ac"), 4), (("aabb", "ab"), 6)]; + + for ((text, pattern), expected) in test_cases { + assert_eq!( + S::maximum_subsequence_count(text.to_string(), pattern.to_string()), + expected, + ); + } + } +}