[LeetCode] Maximize the Confusion of an Exam

2024. Maximize the Confusion of an Exam

A teacher is writing a test with n true/false questions, with ‘T’ denoting true and ‘F’ denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row).

You are given a string answerKey, where answerKey[i] is the original answer to the ith question. In addition, you are given an integer k, the maximum number of times you may perform the following operation:

  • Change the answer key for any question to ‘T’ or ‘F’ (i.e., set answerKey[i] to ‘T’ or ‘F’).

Return the maximum number of consecutive ‘T’s or ‘F’s in the answer key after performing the operation at most k times.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
int helper(string& S, int k, char t) {
int res = 0, l = 0, r = 0, n = S.length(), inc = 0;
while(r < n) {
while(r < n and inc <= k) {
res = max(res, r - l);
if(S[r++] == t) inc++;
}
if(inc <= k)
res = max(res, r - l);
while(l < r and inc > k) {
if(S[l++] == t) inc--;
}
}
return res;
}
public:
int maxConsecutiveAnswers(string S, int k) {
return max(helper(S, k, 'T'), helper(S, k, 'F'));
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/11/PS/LeetCode/maximize-the-confusion-of-an-exam/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.