diff --git a/src/lib.rs b/src/lib.rs index 3b7f1c23..516d2c94 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1404,6 +1404,7 @@ pub mod problem_2011_final_value_of_variable_after_performing_operations; pub mod problem_2012_sum_of_beauty_in_the_array; pub mod problem_2016_maximum_difference_between_increasing_elements; pub mod problem_2022_convert_1d_array_into_2d_array; +pub mod problem_2024_maximize_the_confusion_of_an_exam; pub mod problem_2027_minimum_moves_to_convert_string; pub mod problem_2028_find_missing_observations; pub mod problem_2032_two_out_of_three; diff --git a/src/problem_2024_maximize_the_confusion_of_an_exam/mod.rs b/src/problem_2024_maximize_the_confusion_of_an_exam/mod.rs new file mode 100644 index 00000000..f0d6d959 --- /dev/null +++ b/src/problem_2024_maximize_the_confusion_of_an_exam/mod.rs @@ -0,0 +1,18 @@ +pub mod sliding_window; + +pub trait Solution { + fn max_consecutive_answers(answer_key: String, k: i32) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [(("TTFF", 2), 4), (("TFFT", 1), 3), (("TTFTTFTT", 1), 5)]; + + for ((answer_key, k), expected) in test_cases { + assert_eq!(S::max_consecutive_answers(answer_key.to_string(), k), expected); + } + } +} diff --git a/src/problem_2024_maximize_the_confusion_of_an_exam/sliding_window.rs b/src/problem_2024_maximize_the_confusion_of_an_exam/sliding_window.rs new file mode 100644 index 00000000..14a2c398 --- /dev/null +++ b/src/problem_2024_maximize_the_confusion_of_an_exam/sliding_window.rs @@ -0,0 +1,49 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn max_consecutive_answers(answer_key: String, k: i32) -> i32 { + let answer_key = answer_key.into_bytes(); + let k = k as u32; + let mut window_start = 0; + let mut window_false_count = 0; + let mut window_true_count = 0; + + for &c in &answer_key { + if c == b'F' { + window_false_count += 1; + } else { + window_true_count += 1; + } + + if window_false_count.min(window_true_count) > k { + if answer_key[window_start] == b'F' { + window_false_count -= 1; + } else { + window_true_count -= 1; + } + + window_start += 1; + } + } + + (answer_key.len() - window_start) as _ + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn max_consecutive_answers(answer_key: String, k: i32) -> i32 { + Self::max_consecutive_answers(answer_key, k) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +}