#2024
Medium Algorithms Maximize the confusion of an exam
String Binary Search Sliding Window Prefix Sum
69.7% acceptance
Feb 25, 2026
3079
54
A teacher is writing a test with 'T' or 'F' questions. Maximize consecutive same answers by changing at most k answers.
Return the maximum number of consecutive 'T's or 'F's after at most k operations.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn max_consecutive_answers(answer_key: String, k: i32) -> i32 {
let s: Vec<u8> = answer_key.bytes().collect();
let max_window = |target: u8| -> i32 {
let mut left = 0;
let mut count = 0; // count of non-target chars
let mut best = 0;
for right in 0..s.len() {
if s[right] != target { count += 1; }
while count > k as usize {
if s[left] != target { count -= 1; }
left += 1;
}
best = best.max(right - left + 1);
}
best as i32
};
max_window(b'T').max(max_window(b'F'))
}
}