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:
'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.
Example 1:
Input: answerKey = "TTFF", k = 2
Output: 4
Explanation: We can replace both the 'F's with 'T's to make answerKey = "TTTT".
There are four consecutive 'T's.
Example 2:
Input: answerKey = "TFFT", k = 1
Output: 3
Explanation: We can replace the first 'T' with an 'F' to make answerKey = "FFFT".
Alternatively, we can replace the second 'T' with an 'F' to make answerKey = "TFFF".
In both cases, there are three consecutive 'F's.
Example 3:
Input: answerKey = "TTFTTFTT", k = 1
Output: 5
Explanation: We can replace the first 'F' to make answerKey = "TTTTTFTT"
Alternatively, we can replace the second 'F' to make answerKey = "TTFTTTTT".
In both cases, there are five consecutive 'T's.
Constraints:
n
== answerKey.length
n
<= 5 * 104answerKey[i]
is either 'T'
or 'F'
k
<= n
class Solution:
def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
ans = k
counter = Counter(answerKey[:k])
left = 0
for right in range(k, len(answerKey)):
counter[answerKey[right]] += 1
while min(counter['T'], counter['F']) > k:
counter[answerKey[left]] -= 1
left += 1
ans = max(ans, right - left + 1)
return ans
Ron ChenFri, Jul 7, 2023
function maxConsecutiveAnswers(answerKey, k) {
let max = 0;
let left = 0;
let countT = 0;
let countF = 0;
for (let i = 0; i < answerKey.length; i++) {
if (answerKey[i] === 'F') countF++;
while (countF > k) {
if (answerKey[left] === 'F') countF--;
left++;
}
max = Math.max(max, i - left + 1);
}
left = 0;
for (let i = 0; i < answerKey.length; i++) {
if (answerKey[i] === 'T') countT++;
while (countT > k) {
if (answerKey[left] === 'T') countT--;
left++;
}
max = Math.max(max, i - left + 1);
}
return max;
}
做了一週sliding window,終於一次過了,思路跟前天的1493題一樣,只是這次T跟F都要各數一次。
MarsgoatFri, Jul 7, 2023
public class Solution {
public int MaxConsecutiveAnswers(string answerKey, int k) {
int max = 0;
int left = 0;
int tCount = 0;
int fCount = 0;
for (int right = 0; right < answerKey.Length; right++) {
if (answerKey[right] == 'T') {
tCount++;
} else {
fCount++;
}
while (tCount > k && fCount > k) {
if (answerKey[left++] == 'T') {
tCount--;
} else {
fCount--;
}
}
max = Math.Max(max, right - left + 1);
}
return max;
}
}
JimJul 8, 2023