Skip to content

Commit

Permalink
Add problem 1713: Minimum Operations to Make a Subsequence
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Dec 14, 2023
1 parent 55627c2 commit 4a41fea
Show file tree
Hide file tree
Showing 3 changed files with 69 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 @@ -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;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
pub struct Solution;

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

use std::collections::HashMap;

impl Solution {
pub fn min_operations(target: Vec<i32>, arr: Vec<i32>) -> i32 {
let ranks = (0_u32..)
.zip(target)
.map(|(i, num)| (num, i))
.collect::<HashMap<_, _>>();

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<i32>, arr: Vec<i32>) -> i32 {
Self::min_operations(target, arr)
}
}

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

pub trait Solution {
fn min_operations(target: Vec<i32>, arr: Vec<i32>) -> i32;
}

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

pub fn run<S: Solution>() {
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);
}
}
}

0 comments on commit 4a41fea

Please sign in to comment.