Skip to content

Commit

Permalink
Add problem 2370: Longest Ideal Subsequence
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Dec 25, 2024
1 parent ff53b08 commit d1ed1f7
Show file tree
Hide file tree
Showing 3 changed files with 57 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 @@ -1763,6 +1763,7 @@ pub mod problem_2365_task_scheduler_ii;
pub mod problem_2366_minimum_replacements_to_sort_the_array;
pub mod problem_2367_number_of_arithmetic_triplets;
pub mod problem_2368_reachable_nodes_with_restrictions;
pub mod problem_2370_longest_ideal_subsequence;

#[cfg(test)]
mod test_utilities;
38 changes: 38 additions & 0 deletions src/problem_2370_longest_ideal_subsequence/dynamic_programming.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
fn fold_max(s: &[u32]) -> u32 {
s.iter().fold(0, |max, &x| max.max(x))
}

pub fn longest_ideal_string(s: String, k: i32) -> i32 {
let k = k as u32 as usize;
let mut cache = [0_u32; 26];

for c in s.into_bytes() {
let c = usize::from(c - b'a');

cache[c] = Self::fold_max(&cache[c.saturating_sub(k)..=(c + k).min(25)]) + 1;
}

Self::fold_max(&cache) as _
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn longest_ideal_string(s: String, k: i32) -> i32 {
Self::longest_ideal_string(s, k)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
18 changes: 18 additions & 0 deletions src/problem_2370_longest_ideal_subsequence/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod dynamic_programming;

pub trait Solution {
fn longest_ideal_string(s: String, k: i32) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [(("acfgbd", 2), 4), (("abcd", 3), 4)];

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

0 comments on commit d1ed1f7

Please sign in to comment.