Maximize the Confusion of an Exam — LeetCode 2024 Python Solution
- Problem
- #2024
- Pattern
- Sliding Window
- Reading time
- 2 min
- Source
- leetcode.com
The 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).
Example
- Input
- answerKey = "TTFF", k = 2
- Output
- 4
- Explanation
- We can replace both the 'F's with 'T's to make answerKey = "TTTT".
Python solution
class Solution:
def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
def f(c: str) -> int:
cnt = l = 0
for ch in answerKey:
cnt += ch == c
if cnt > k:
cnt -= answerKey[l] == c
l += 1
return len(answerKey) - l
return max(f("T"), f("F"))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) to O(n) auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2024. Maximize the Confusion of an Exam is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2024. Maximize the Confusion of an Exam?
- LeetCode 2024. Maximize the Confusion of an Exam is rated Medium on LeetCode.
- What topics does LeetCode 2024. Maximize the Confusion of an Exam cover?
- LeetCode 2024. Maximize the Confusion of an Exam is tagged String, Binary Search, Prefix Sum and Sliding Window on LeetCode.