diff --git a/src/lib.rs b/src/lib.rs index 3dfbd630..3f177912 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1280,6 +1280,7 @@ pub mod problem_1706_where_will_the_ball_fall; pub mod problem_1710_maximum_units_on_a_truck; pub mod problem_1711_count_good_meals; pub mod problem_1712_ways_to_split_array_into_three_subarrays; +pub mod problem_1713_minimum_operations_to_make_a_subsequence; pub mod problem_1716_calculate_money_in_leetcode_bank; pub mod problem_1717_maximum_score_from_removing_substrings; pub mod problem_1718_construct_the_lexicographically_largest_valid_sequence; diff --git a/src/problem_1713_minimum_operations_to_make_a_subsequence/longest_increasing_subsequence.rs b/src/problem_1713_minimum_operations_to_make_a_subsequence/longest_increasing_subsequence.rs new file mode 100644 index 00000000..55ff7dbf --- /dev/null +++ b/src/problem_1713_minimum_operations_to_make_a_subsequence/longest_increasing_subsequence.rs @@ -0,0 +1,47 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +use std::collections::HashMap; + +impl Solution { + pub fn min_operations(target: Vec, arr: Vec) -> i32 { + let ranks = (0_u32..) + .zip(target) + .map(|(i, num)| (num, i)) + .collect::>(); + + let mut length_to_min_index = Vec::with_capacity(ranks.len()); + + for target in arr { + if let Some(&rank) = ranks.get(&target) { + let length = length_to_min_index.partition_point(|&left_index| left_index < rank); + + #[allow(clippy::option_if_let_else)] // False positive. + if let Some(min_rank) = length_to_min_index.get_mut(length) { + *min_rank = rank; + } else { + length_to_min_index.push(rank); + } + } + } + + (ranks.len() - length_to_min_index.len()) as _ + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn min_operations(target: Vec, arr: Vec) -> i32 { + Self::min_operations(target, arr) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_1713_minimum_operations_to_make_a_subsequence/mod.rs b/src/problem_1713_minimum_operations_to_make_a_subsequence/mod.rs new file mode 100644 index 00000000..13b57f2e --- /dev/null +++ b/src/problem_1713_minimum_operations_to_make_a_subsequence/mod.rs @@ -0,0 +1,21 @@ +pub mod longest_increasing_subsequence; + +pub trait Solution { + fn min_operations(target: Vec, arr: Vec) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + ((&[5, 1, 3] as &[_], &[9, 4, 2, 3, 4] as &[_]), 2), + ((&[6, 4, 8, 1, 3, 2], &[4, 7, 6, 2, 3, 8, 6, 1]), 3), + ]; + + for ((target, arr), expected) in test_cases { + assert_eq!(S::min_operations(target.to_vec(), arr.to_vec()), expected); + } + } +}