Skip to content

Commit

Permalink
Add problem 2207: Maximize Number of Subsequences in a String
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Sep 12, 2024
1 parent 5f5bd2c commit 4846f8c
Show file tree
Hide file tree
Showing 3 changed files with 58 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 @@ -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;
Expand Down
Original file line number Diff line number Diff line change
@@ -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::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -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<S: Solution>() {
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,
);
}
}
}

0 comments on commit 4846f8c

Please sign in to comment.