Skip to content

Commit

Permalink
Add problem 2024: Maximize the Confusion of an Exam
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jan 12, 2024
1 parent e6728bc commit 4f59670
Show file tree
Hide file tree
Showing 3 changed files with 68 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 @@ -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;
Expand Down
18 changes: 18 additions & 0 deletions src/problem_2024_maximize_the_confusion_of_an_exam/mod.rs
Original file line number Diff line number Diff line change
@@ -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<S: Solution>() {
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);
}
}
}
Original file line number Diff line number Diff line change
@@ -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::<super::Solution>();
}
}

0 comments on commit 4f59670

Please sign in to comment.