Maximize the Confusion of an Exam - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: answerKey = "TTFF", k = 2
Output: 4
💡 Note: We can change at most 2 characters. Change both F's to T's to get "TTTT" with length 4, or change both T's to F's to get "FFFF" with length 4.
Example 2 — Mixed Pattern
$ Input: answerKey = "TFFT", k = 1
Output: 3
💡 Note: We can change 1 character. Change the middle F to T to get "TTFT" or "TFTT", giving us a maximum consecutive length of 3 T's.
Example 3 — No Changes Needed
$ Input: answerKey = "TTTTTTTT", k = 2
Output: 8
💡 Note: All characters are already the same, so we don't need any changes. The entire string has length 8.

Constraints

  • 1 ≤ answerKey.length ≤ 5 × 104
  • answerKey[i] is either 'T' or 'F'
  • 0 ≤ k ≤ answerKey.length

Visualization

Tap to expand
Maximize the Confusion of an Exam INPUT answerKey String: T i=0 T i=1 F i=2 F i=3 Parameters: answerKey = "TTFF" k = 2 (max changes) Goal: Find max consecutive same answers after changing at most k characters ALGORITHM STEPS 1 Sliding Window Use two pointers (left, right) 2 Count Target Char Track T's and F's in window 3 Shrink if Needed If min(T,F) > k, move left 4 Track Max Length Update max window size Window Expansion: T T F F len=4 Change 2 F's --> T's: T T T T 4 T's! FINAL RESULT Maximum Consecutive Same Answers: T T T T 4 consecutive Output: 4 Explanation: With k=2 changes, we can convert both F's to T's, resulting in "TTTT" = 4 T's Key Insight: Use sliding window technique to find the longest substring where the count of the minority character (either T or F) is at most k. Run two passes: one maximizing T's and one maximizing F's, then return the maximum. Time: O(n), Space: O(1). The window shrinks only when we'd need more than k changes. TutorialsPoint - Maximize the Confusion of an Exam | Sliding Window Approach
Asked in
Facebook 35 Amazon 28 Google 22
32.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen