Maximize the Confusion of an Exam - Problem
A teacher is preparing a true/false exam to maximize student confusion by creating the longest possible sequence of consecutive identical answers. The exam consists of n questions, where each answer is either 'T' (True) or 'F' (False).
You are given a string answerKey representing the original answers, and an integer k representing the maximum number of answers you can change. Your goal is to find the maximum length of consecutive identical answers (all T's or all F's) after making at most k changes.
Example: If answerKey = "TTFTTFTT" and k = 1, you could change one 'F' to 'T' to get "TTTTTFTT", creating a sequence of 5 consecutive T's.
Input & Output
example_1.py โ Basic case with k=1
$
Input:
answerKey = "TTFF", k = 2
โบ
Output:
4
๐ก Note:
We can change both F's to T's to get "TTTT", or change both T's to F's to get "FFFF". Either way gives us 4 consecutive identical answers.
example_2.py โ Mixed string with limited changes
$
Input:
answerKey = "TFFT", k = 1
โบ
Output:
3
๐ก Note:
We can change the middle F to T to get "TTFT" (3 consecutive T's at start), or change a T to F to get "TFFF" (3 consecutive F's at end). Maximum is 3.
example_3.py โ All same characters
$
Input:
answerKey = "TTTT", k = 2
โบ
Output:
4
๐ก Note:
The string already has 4 consecutive T's, so no changes needed. We don't need to use any of our k=2 changes.
Constraints
- n == answerKey.length
- 1 โค n โค 5 ร 104
- answerKey[i] is either 'T' or 'F'
- 0 โค k โค n
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Start with empty window, trying to maximize T's
2
Expand
Expand right pointer, count F's (characters to change)
3
Contract
When F count > k, shrink from left until valid
4
Track Maximum
Keep track of largest valid window size seen
5
Repeat for F's
Do the same process trying to maximize F's
Key Takeaway
๐ฏ Key Insight: Sliding window allows us to efficiently find the longest subarray where minority characters โค k, avoiding the need to check all possible subarrays.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code